How to count the number of matches in a regular expression?

For example, I would like to calculate how many numbers are in a string using a regular expression like: [0-9]

+5
source share
5 answers
Regex.Matches(text, pattern).Count
+12
source
Regex.Matches(input, @"\d").Count

Since this will be the allocation of a match instance for each match, this may be suboptimal in performance. My instinct would be to do something like the following:

input.Count(Char.IsDigit)
+4
source
        var a = new Regex("[0-9]");
        Console.WriteLine(a.Matches("1234").Count);
        Console.ReadKey();
+2

MatchCollection, RegEx, .

However, I suspect that this may not be an account that is erroneous, but you may need to be more specific with your regular expression (make it less greedy) in order to identify specific instances of the match you want.

Now you have all instances of the same number in the string, so you get a result that you think is incorrect? If so, can you provide a string and a regular expression?

0
source
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
-1
source

All Articles