Regular expression that doesn't contain certain string

Jakub Arnold picture Jakub Arnold · Apr 4, 2009 · Viewed 185.5k times · Source

I have something like this

aabbabcaabda

for selecting minimal group wrapped by a I have this /a([^a]*)a/ which works just fine

But i have problem with groups wrapped by aa, where I'd need something like /aa([^aa]*)aa/ which doesn't work, and I can't use the first one like /aa([^a]*)aa/, because it would end on first occurence of a, which I don't want.

Generally, is there any way, how to say not contains string in the same way that I can say not contains character with [^a]?

Simply said, I need aa followed by any character except sequence aa and then ends with aa

Answer

Grey Panther picture Grey Panther · Mar 5, 2010

By the power of Google I found a blogpost from 2007 which gives the following regex that matches string which don't contains a certain substring:

^((?!my string).)*$

It works as follows: it looks for zero or more (*) characters (.) which do not begin (?! - negative lookahead) your string and it stipulates that the entire string must be made up of such characters (by using the ^ and $ anchors). Or to put it an other way:

The entire string must be made up of characters which do not begin a given string, which means that the string doesn't contain the given substring.