tags:

views:

83

answers:

4

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

+5  A: 
Regex.Matches(text, pattern).Count
Aviad P.
+3  A: 
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)
nullptr
A: 

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?

casperOne
+1  A: 
        var a = new Regex("[0-9]");
        Console.WriteLine(a.Matches("1234").Count);
        Console.ReadKey();
rdkleine