简体   繁体   English

如何计算正则表达式的匹配次数?

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

例如,我想使用正则表达式计算一个字符串中有多少个数字:[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. 由于这将为每个匹配项分配一个Match实例,因此在性能方面可能不是最佳的。 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. 从对RegEx的Matches方法的调用返回的MatchCollection实例将为您提供匹配数的计数。

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? 如果可以,可以提供字符串和正则表达式吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM