简体   繁体   English

如何计算由ASP.Net MVC中的正则表达式捕获的匹配数?

[英]How to count the number of matches captured by the regex in ASP.Net MVC?

I'm having a problem counting the number of matches captured by the regex because it doesn't have a count function. 我在计算正则表达式捕获的匹配数时遇到问题,因为它没有计数功能。

Here is my code: 这是我的代码:

 var pathRegex = new Regex(".+?\\:\\/\\/.+? (\\/.+?)(?:#|\\?|$)");
 var result = pathRegex.Match(url);
            if (!(result.Success))
            {
                pathRegex = new Regex("/\\/.*/");
                result = pathRegex.Match(url);

                if (result.Success && result.Length == 1)
                {
                    return result.Value;
                }else
                {
                    return "";
                } 
            }

I've tried result.Length but it only counts the length of the string that has a match. 我已经尝试过result.Length但是它只计算具有匹配项的字符串的长度。 Do you have any suggestions or workaround on this? 您对此有任何建议或解决方法吗?

MatchCollection matches = pathRegex.Matches(url);
var count = matches.Count;

Regex Class 正则表达式类

Regex.Match only returns the first occurrence as a single Match object. Regex.Match仅将第一个匹配项作为单个Match对象返回。 Ref . 参考 Therefore, it Count is not available and if (result.Success) is sufficient for your case. 因此,该Count不可用, if (result.Success)是否足以满足您的情况。

If you want multiple matches you need Regex.Matches which returns a MatchCollection. 如果需要多个匹配项,则需要Regex.Matches ,它返回一个MatchCollection。

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

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