How do I count the number of matches by a regex?
For example, I would li开发者_JAVA百科ke to count how many numbers are in a string using a regex like: [0-9]
Regex.Matches(text, pattern).Count
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)
var a = new Regex("[0-9]");
Console.WriteLine(a.Matches("1234").Count);
Console.ReadKey();
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?
.NET 7 introduced the Count
method.
using System.Text.RegularExpressions;
string content = @"Foxes are omnivorous mammals belonging to several genera
of the family Canidae. Foxes have a flattened skull, upright triangular ears,
a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every
continent except Antarctica. By far the most common and widespread species of
fox is the red fox.";
string pattern = "fox(es)?";
int n = Regex.Count(content, pattern, RegexOptions.Compiled |
RegexOptions.IgnoreCase);
Console.WriteLine($"There are {n} matches");
It has both static and instance overloads of the method.
var rx = new Regex(pattern, RegexOptions.Compiled |
RegexOptions.IgnoreCase);
int n = rx.Count(content);
Console.WriteLine($"There are {n} matches");
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
精彩评论