我需要一个正则表达式来匹配不在一组单词中的单词。我用谷歌搜索和堆积问题,发现了一些建议。但它们都是关于匹配一组字符,而不是单词。所以我试着自己写一个正则表达式。但我找不到正确的正则表达式。这是我到目前为止尝试的最后一个:
(?:(?!office|blog).)+
我的话是office
,和article
。我想要输入不在此组中的单词。你能帮我吗?
我需要一个正则表达式来匹配不在一组单词中的单词。我用谷歌搜索和堆积问题,发现了一些建议。但它们都是关于匹配一组字符,而不是单词。所以我试着自己写一个正则表达式。但我找不到正确的正则表达式。这是我到目前为止尝试的最后一个:
(?:(?!office|blog).)+
我的话是office
,和article
。我想要输入不在此组中的单词。你能帮我吗?
我认为你的正则表达式应该是这样的:
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).)*$
这是什么意思:
重要的是,这一次只匹配一个字符,并且在匹配每个字符后,检查以确保“badword”不会立即出现。