[英]C# Regex partial string match
每個人,如果輸入是badword,我有以下函數返回true
public bool isAdultKeyword(string input)
{
if (input == null || input.Length == 0)
{
return false;
}
else
{
Regex regex = new Regex(@"\b(badword1|badword2|anotherbadword)\b");
return regex.IsMatch(input);
}
}
上面的函數只匹配整個字符串,即如果輸入badword它不匹配但輸入時將是bawrod1。
我試圖做的是當輸入的一部分包含一個壞詞時獲得匹配
嘗試:
Regex regex = new Regex(@"(\bbadword1\b|\bbadword2\b|\banotherbadword\b)");
return regex.IsMatch(input);
你的方法似乎工作正常。 你能澄清一下它有什么問題嗎? 我的下面的測試程序顯示它通過了許多測試而沒有失敗。
using System;
using System.Text.RegularExpressions;
namespace CSharpConsoleSandbox {
class Program {
public static bool isAdultKeyword(string input) {
if (input == null || input.Length == 0) {
return false;
} else {
Regex regex = new Regex(@"\b(badword1|badword2|anotherbadword)\b");
return regex.IsMatch(input);
}
}
private static void test(string input) {
string matchMsg = "NO : ";
if (isAdultKeyword(input)) {
matchMsg = "YES: ";
}
Console.WriteLine(matchMsg + input);
}
static void Main(string[] args) {
// These cases should match
test("YES badword1");
test("YES this input should match badword2 ok");
test("YES this input should match anotherbadword. ok");
// These cases should not match
test("NO badword5");
test("NO this input will not matchbadword1 ok");
}
}
}
輸出:
YES: YES badword1
YES: YES this input should match badword2 ok
YES: YES this input should match anotherbadword. ok
NO : NO badword5
NO : NO this input will not matchbadword1 ok
所以根據你的邏輯,你會匹配屁股嗎?
此外,請記住經典的地方Scunthorpe - 您的成人過濾器需要能夠通過這個詞。
你可能不必以這么復雜的方式去做,但你可以嘗試實現Knuth-Morris-Pratt 。 我曾嘗試在我失敗的(完全是我的錯誤)OCR增強器模塊中使用它。
\\ b是正則表達式中的單詞邊界嗎?
在這種情況下,您的正則表達式僅查找整個單詞。 刪除這些將匹配壞詞的任何出現,包括它作為較大單詞的一部分被包括在內的位置。
Regex regex = new Regex(@"(bad|awful|worse)", RegexOptions.IgnoreCase);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.