Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a regular expression that will not match if a string contains a particular substring?

Tags:

string

regex

Example:

Suppose in the following example I want to match strings that do not contain the word "NOOOT".
Example A: This shirt is NOOOT black.
Example B: This shirt is black.

I want something a little bit like the like the non-matching character class (e.g. [^abc]), but for whole strings:
.*?(^NOOOT).*?

Does such a creature exist?

like image 644
Iain Fraser Avatar asked Dec 29 '22 22:12

Iain Fraser


2 Answers

^(?:(?!NOOOT).)*$

Explanation:

^ start of string

(?!NOOOT). assert that it's not possible to match NOOOT at the current position, then match any character.

(?: ...)* do this any number of times until...

$ end of string.

like image 145
Tim Pietzcker Avatar answered May 14 '23 02:05

Tim Pietzcker


You can do that wit a negative lookahead assertion (?!…):

^(?:(?!NOOOT).)*$

This one matches only if there is no NOOOT ahead at the current position while proceeding character by character.

It’s also possible to do that with basic syntax. But that’s more complex.

like image 30
Gumbo Avatar answered May 14 '23 02:05

Gumbo