简体   繁体   中英

C# Regex.Match stop match when meet special characters

This is my code:

// Clear strange characters
String string1 = "d34-&%#*%(#**)2121js3412h";
String string2 = Regex.Match(string1, @"\d+").Value;
Console.WriteLine(string2);

The output of above code is: 34 .
The expected output is: 3421213412 .

Why does the Match stop matching at the "-" character (or any special character)?
Did I miss some regex rules?

您可以随时使用Regex.Replace

string string2 = Regex.Replace(string1, @"[^0-9]", "");

If you want all matches, use Regex.Matches :

var matches = Regex.Matches(string1, @"\d+").Cast<Match>().Select(x => x.Value);
string string2 = string.Concat(matches);

It has nothing to do with special characters. That is the behaviour of Match method, it returns the first match it found.

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