C#Regex部分字符串匹配

时间:2009-02-11 09:49:11

标签: c# regex

每个人,如果输入是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。

我试图做的是当输入的一部分包含一个坏词时获得匹配

5 个答案:

答案 0 :(得分:1)

所以根据你的逻辑,你会匹配屁股吗?

另外,请记住经典的地方Scunthorpe - 您的成人过滤器需要能够通过这个词。

答案 1 :(得分:1)

您可能不必以这么复杂的方式执行此操作,但您可以尝试实现Knuth-Morris-Pratt。我曾尝试在我失败的(完全是我的错误)OCR增强器模块中使用它。

答案 2 :(得分:1)

尝试:

Regex regex = new Regex(@"(\bbadword1\b|\bbadword2\b|\banotherbadword\b)"); 
return regex.IsMatch(input);

答案 3 :(得分:1)

你的方法似乎工作正常。你能澄清一下它有什么问题吗?我的下面的测试程序显示它通过了许多测试而没有失败。

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

答案 4 :(得分:0)

\ b是正则表达式中的单词边界吗?

在这种情况下,您的正则表达式仅查找整个单词。 删除这些将匹配坏词的任何出现,包括它被包含在更大词的一部分。

Regex regex = new Regex(@"(bad|awful|worse)", RegexOptions.IgnoreCase);