[英]C#: Regex to do NOT match to a group of words
我需要一個正則表達式來匹配不在一組單詞中的單詞。 我用google搜索和Stacked問題找到了一些建議。 但他們都是關於匹配一組字符,而不是單詞。 所以我試着自己寫一個正則表達式。 但我找不到正確的正則表達式。 這是我迄今為止嘗試的最后一個:
(?:(?!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”不會立即跟隨。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.