C#:正则表达式与一组单词不匹配

时间:2013-01-03 19:50:43

标签: c# regex c#-4.0 regex-negation

我需要一个正则表达式来匹配不在一组单词中的单词。我用google搜索和Stacked问题找到了一些建议。但他们都是关于匹配一组字符,而不是单词。所以我试着自己写一个正则表达式。但我找不到正确的正则表达式。这是我迄今为止尝试的最后一个:

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

我的字是officearticle。我想要输入不在此组中的单词。你能帮帮我吗?

3 个答案:

答案 0 :(得分:5)

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

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;
   ...
}

这将返回“The”,“is”,“closed”,“please”,“visit”和“our”。

答案 1 :(得分:0)

不清楚您的问题。因为您尝试使用 office | blog 的正则​​表达式模式,但在下一行中您说的是 office 文章。哦,我在这里尝试这3个字(办公室,博客,文章)。根据您的需要使用它,

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());
}

<强>输出:

  

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

答案 2 :(得分:0)

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

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

含义:

  • ^ $:仅匹配整个搜索字符串(开头(^)和结束($))。
  • ()*:匹配0或更多内容。
  • (?!badword):向前看当前角色,并确保“badword”整体不匹配。
  • :匹配任何单个字符。

重要的是,这一次只匹配一个字符,并且在匹配每个字符后,检查以确保“badword”不会立即跟随。

相关问题