Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#正则表达式部分字符串匹配_C#_Regex - Fatal编程技术网

C#正则表达式部分字符串匹配

C#正则表达式部分字符串匹配,c#,regex,C#,Regex,各位,如果输入是坏字,我有下面的函数返回true public bool isAdultKeyword(string input) { if (input == null || input.Length == 0) { return false; } else { Regex regex = new Regex(@"\b(badword1|badword2|anotherbadword)\b"); retur

各位,如果输入是坏字,我有下面的函数返回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);
    }
}
上述函数仅与整个字符串匹配,即如果输入的是bawrod1,则不会匹配,但当输入为bawrod1时会匹配


我想做的是,当输入的一部分包含一个坏话时,获得匹配,所以在你的逻辑下,你会匹配ass吗


另外,请记住经典的斯肯索普(Scunthorpe)——您的成人过滤器需要能够允许这个单词通过。

您可能不需要以如此复杂的方式完成,但您可以尝试实现。我曾尝试在一个失败(完全是我的错)的OCR增强器模块中使用它。

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

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

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


你的方法似乎很有效。你能澄清一下它有什么问题吗?下面我的测试程序显示它通过了大量测试,没有失败

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

“斯肯索普”你住在那里吗?你为什么知道那个城市Pinput将是子域名(单个单词),我假设“as”不会匹配as,因为坏单词列表中不会有“as”,而是“ass”
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