[英]How to count the number of matches captured by the regex in ASP.Net MVC?
我在計算正則表達式捕獲的匹配數時遇到問題,因為它沒有計數功能。
這是我的代碼:
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 "";
}
}
我已經嘗試過result.Length
但是它只計算具有匹配項的字符串的長度。 您對此有任何建議或解決方法嗎?
MatchCollection matches = pathRegex.Matches(url);
var count = matches.Count;
Regex.Match
僅將第一個匹配項作為單個Match對象返回。 參考 因此,該Count
不可用, if (result.Success)
是否足以滿足您的情況。
如果需要多個匹配項,則需要Regex.Matches
,它返回一個MatchCollection。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.