[英]To check whether there are words matching in a sentence with c# regular expression
我有一個接受2個參數的函數。 參數1:SearchTerm,參數2:ProductName
如何檢查ProductName中是否存在SearchTerm中的單詞,不管它出現在ProductName的開頭,中間還是結尾?
它必須逐字匹配,假設SearchTerm =“ cano”,ProductName =“ canon”,則應返回false,而不匹配。
如果您只想匹配完整的單詞,則需要單詞邊界 \\b
,以便在搜索詞之前和之后添加。
\\b
是零寬度斷言,它與從單詞到非單詞字符或從非單詞到單詞字符的變化匹配。
String term = "Foo";
String[] text = { "This contains Foo bar.", "Foo.", "Foobar", "BarFoo", "foo" };
Regex reg = new Regex(@"\b" + Regex.Escape(term) + @"\b");
foreach (var item in text) {
Match word = reg.Match(item);
if (word.Success) {
Console.WriteLine(item + ": valid");
}
else {
Console.WriteLine(item + ": invalid");
}
}
輸出:
這包含Foo酒吧。 =>有效
富。 =>有效
Foobar =>無效
BarFoo =>無效
foo =>無效
因為您希望能夠指定它是一個單獨的詞而不是子詞,所以需要使用regexes 。
如果您要搜索的單詞存儲在變量“ lol”中,則您的正則表達式可能看起來像這樣:
Regex regex1 = new Regex(lol + @"[^a-Z]"); // include grammar marks to avoid issues like "can." not matching
本質上,您只想匹配該單詞,並確保其后的字符不是另一個字母。 這樣,您知道這不是另一個詞。
編輯 :嘗試這種美麗。 我自己學了點東西。
string sPattern = @"\b" + lol + @"\b";
Edit2 :看起來手鐲首先得到它。 這是我使用的頁面,僅供參考。
您不需要正則表達式即可進行簡單的字符串搜索。
ProductName.Contains(searchTerm);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.