Search code examples
c#regexregex-lookaroundsnegative-lookbehind

How to match a string that doesnt contain a pattern


I am trying to write a regex template that matches all the strings that doesn't contain a certain template.

E.g.:

Matches:

This is my friend. He is very nice. 

in

This is my friend. He is very nice. 

but doesn't match anything in :

  This is my friend John Michaels Fredrickson. He is very nice. 

Because it contains something like this: ([A-Z][a-z]+\s?){3}


Solution

  • You can use negative lookahead:

    ^(?!.*?([A-Z][a-z]+\W){3}).*$
    

    RegEx Demo