繁体   English   中英

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

[英]C#: Regex to do NOT match to a group of words

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

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

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

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

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”。

不清楚你的问题清楚。因为你试图办公室|博客的正则表达式模式,但在下一行,你说你的话是办公室文章。哦,我尝试这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());
}

输出:

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

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

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

这是什么意思:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM