c#: Regex不匹配一组单词

本文关键字:一组 单词 Regex 不匹配 | 更新日期: 2023-09-27 17:50:46

我需要一个正则表达式来匹配不在一组单词中的单词。我已经谷歌和堆叠问题,并找到了一些建议。但它们都是关于匹配一组字符,而不是单词。所以我试着自己写一个正则表达式。但是我找不到正确的正则表达式。这是我到目前为止尝试的最后一个:

(?:(?!office|blog).)+

我的词是officearticle。我希望输入的单词不在这个组中。你能帮我一下吗?

c#: Regex不匹配一组单词

我认为你的正则表达式应该是这样的:

Regex r = new Regex(@"'b(?!office|blog|article)'w+'b");
MatchCollection words = r.Matches("The office is closed, please visit our blog");
foreach(Match word in words)
{
   string legalWord = word.Groups[0].Value;
   ...
}

这将返回"的","是"、"封闭"、"请"、"访问"answers"我们"。

我不太清楚你的问题。因为您尝试使用office|blog的正则表达式模式,但在下一行中您说您的单词是officearticle。好吧,我试试这三个词(办公室,博客,文章)。作为你的需要,

Pattern pattern = Pattern.compile("(''w+|''W)");
Matcher m = pattern.matcher("Now the office is closed,so i spend time with blog and article writing");
while (m.find())
{
    Pattern pattern1 = Pattern.compile("office|blog|article"); //change it as your need
    Matcher m1 = pattern1.matcher(m.group());
    if(m1.find())
    {
        System.out.print(m.group().replace(m.group(),""));
    }
    else
        System.out.print(m.group());
}
输出:

现在关闭了,所以我花时间和写作

尝试自己解决这个问题。在这里找到了我的答案:http://www.regextester.com/15

正则表达式:^((?!badword).)*$

含义:

  • ^$:只匹配整个搜索字符串(开始(^)和结束($))。
  • ()*:匹配0个或多个包含的内容。
  • (?!badword):查找当前字符,并确保"badword"作为一个整体不匹配。
  • 。:匹配任意单个字符。

重要的是,这一次只匹配一个字符,并且,在匹配每个字符之后,检查以确保"badword"没有立即跟随