簡體   English   中英

從字符串獲取數字並粘上字符

[英]Getting a numbers from a string with chars glued

我需要恢復粘貼字符串中的每個數字

例如,從以下字符串中:

string test = "number1+3"
string test1 = "number 1+4"

我想恢復(1和3)和(1和4)我該怎么做?

 string test= "number1+3";
 List<int> res; 

 string[] digits= Regex.Split(test, @"\D+");
 foreach (string value in digits)
 {
     int number;
     if (int.TryParse(value, out number))
     {
         res.Add(number)
     }
 }

這個正則表達式應該工作

string pattern = @"\d+";
string test = "number1+3";

foreach (Match match in Regex.Matches(test, pattern))
   Console.WriteLine("Found '{0}' at position {1}", 
                     match.Value, match.Index);

請注意,如果您打算多次使用它,出於性能方面的考慮,創建Regex實例比使用此靜態方法更好。

var res = new List<int>();

var regex = new Regex(@"\d+");

void addMatches(string text) {
    foreach (Match match in regex.Matches(text))
    {
        int number = int.Parse(match.Value);
        res.Add(number);
    }
}

string test = "number1+3";
addMatches(test);

string test1 = "number 1+4";
addMatches(test1);

MSDN鏈接

小提琴1

小提琴2

這需要一個正則表達式:

(\d+)\+(\d+)

測試一下

Match m = Regex.Match(input, @"(\d+)\+(\d+)");

string first = m.Groups[1].Captures[0].Value;
string second = m.Groups[2].Captures[0].Value;

正則表達式的替代方法:

string test = "number 1+4";

int[] numbers = test.Replace("number", string.Empty, StringComparison.InvariantCultureIgnoreCase)
                    .Trim()
                    .Split("+", StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => Convert.ToInt32(x))
                    .ToArray();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM