How do I count the number of matches by a regex?

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!