[英]Regex.Matches not returning expected
使用Regex.Matches
我的印象是您將輸入以下內容:
private static int CheckForWordMatch(string offer, string item)
{
string pattern = @"\b(" + item + ")\b";
int count = 0;
count = Regex.Matches(@offer, pattern).Count;
return count;
}
測試參數:
offer = AK47HyperBeastFieldTested
item = AK47HyperBeastFieldTested
我正在尋找完全匹配的單詞,因此如果該項目為“ AK47HyperBeast”,則不會返回匹配計數2。
我在這里做錯了什么?
您忘了在第二個@)\\b
使用逐字字符串文字。 您的")\\b"
被當作a )
和一個退格字符。
string pattern = @"\b(?:" + item + @")\b";
參見C#演示 :
string offer = "AK47HyperBeastFieldTested";
string item = "AK47HyperBeastFieldTested";
string pattern = @"\b(" + item + @")\b";
int count = Regex.Matches(offer, pattern).Count;
Console.WriteLine(count);
有人建議使用(^|\\b)
和(\\b|$)
-這是多余的,因為\\b
(單詞邊界)已經在那些位置匹配了。
如果您的item
可能以非單詞字符開頭或結尾,但仍需要整個單詞匹配,請使用
string pattern = @"(?<!\w)(" + item + @")(?!\w)";
另外,請注意,僅當您打算使用輪換方式時才需要使用圓括號(例如\\b(word|another)\\b
)。 如果一次只測試一個字,就可以安全地刪除它們。
\\b
是您沒有offer
單詞邊界,請改用
string pattern = @"^\S*(" + item + @")\S*$";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.