Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need a regex to match a word that is not in a group of words. I have googled and Stacked question an found some suggestions. But they all were about matching a group of chars, not words. so I tried to write a regex by myself. But I couldn't find a correct regex. Here is my last one that I have tried until now:

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

my words are office, and article. I want input words that are not in this group. Can you help me please?

like image 469
amiry jd Avatar asked Oct 23 '25 04:10

amiry jd


1 Answers

I think that your Regex should look like this:

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

This will return "The", "is", "closed", "please", "visit" and "our".

like image 109
Casperah Avatar answered Oct 24 '25 19:10

Casperah