如何从字符串混合中提取数字值与C#中的数字和字符? [重复]

时间:2021-02-22 01:59:12

This question already has an answer here:

这个问题在这里已有答案:

I am quite new to regular expression. My requirement is to extract number from string that includes mix of numbers and characters. I have tried below codes but I can only get the first number from string.

我对正则表达式很新。我的要求是从包含数字和字符组合的字符串中提取数字。我试过下面的代码,但我只能从字符串中获取第一个数字。

String serialNumber= "000745 TO 000748,00050-00052"
Match match = Regex.Match(serialNumber), @"(\d)+", RegexOptions.IgnoreCase);

if (match.Success)
{
    int a = Convert.ToInt32(match); // This part not sure how to do
}

Expected result is:

预期结果是:

000745
000748
00050
00052

1 个解决方案

#1


1  

string strRegex = @"\d+";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"000745 TO 000748,00050-00052";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }

}

You need to loop through your matches to get all the matches.

你需要循环你的比赛才能得到所有的比赛。

#1


1  

string strRegex = @"\d+";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"000745 TO 000748,00050-00052";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }

}

You need to loop through your matches to get all the matches.

你需要循环你的比赛才能得到所有的比赛。