简体   繁体   中英

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?

//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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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