简体   繁体   English

C#-使用Regex搜索字符串中的数字

[英]C# - Search for digits in string with Regex

I want to extract digits from a string, formatted as following: 我想从字符串中提取数字,格式如下:

string foo="something%4%something2%5%";

How do I write this with Regex? 我该如何使用Regex编写此代码?

//pseudocode
foo.GetDigits("%"+{int}+"%").ToArray();

Thanks! 谢谢!

var matches = Regex.Matches(foo, @"%(\d+?)%").Cast<Match>()
                   .Select(m => m.Groups[1].Value)
                   .ToList();

Instead of Regex, you can use char.IsDigit method to get all the digits from the string. 可以使用char.IsDigit方法代替正则表达式,以从字符串中获取所有数字。

string str = "something%4%something2%5%";
string digitstr = new string(str.Where(r => char.IsDigit(r)).ToArray());

Or shorter: 或更短:

string digitstr = new string(str.Where(char.IsDigit).ToArray());

You can use this pattern too: 您也可以使用此模式:

(\d+)(?=%)

Here is a sample code: (untested) 以下是示例代码:(未经测试)

MatchCollection mcol = System.Text.RegularExpression.Regex.Matches(foo,"(\d+)(?=%)");

foreach (Match m in mcol)
{
   System.Diagnostic.Debug.Print(m.ToString());
}

This pattern will capture all digit(s) followed by % . 此模式将捕获所有数字,然后是%

hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM