[英]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.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.