For example, I would like to count how many numbers are in a string using a regex like: [0-9]
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Regex.Matches(text, pattern).Count
回答2:
Regex.Matches(input, @"\d").Count
Since this is going to allocate a Match instance for each match, this may be sub-optimal performance-wise. My instinct would be to do something like the following:
input.Count(Char.IsDigit)
回答3:
var a = new Regex("[0-9]"); Console.WriteLine(a.Matches("1234").Count); Console.ReadKey();
回答4:
The MatchCollection instance returned from a call to the Matches method on RegEx will give you the count of the number of matches.
However, what I suspect is that it might not be the count that is wrong, but you might need to be more specific with your regular expression (make it less greedy) in order to determine the specific instances of the match you want.
What you have now should give you all instances of a single number in a string, so are you getting a result that you believe is incorrect? If so, can you provide the string and the regex?
回答5:
var regex = new Regex(@"\d+"); var input = "123 456"; Console.WriteLine(regex.Matches(input).Count); // 2 // we want to count the numbers, not the number of digits