Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Match Entire String Unless [duplicate]

Tags:

regex

I need to write a regular expression that will match everything in the string unless it has a certain word in it. Taking this string for example:

http://12.34.567.890/sqlbuddy

The expression that matches everything is:

^.*$

...Which needs to be modified so that it will not match the string at all if it contains the word "sqlbuddy". I thought that a negative lookahead would do it, but that's not working for me.

For example, I tried this, which doesn't work:

^(?!sqlbuddy).*$

How should I modify this?

like image 610
Allen Avatar asked Aug 02 '11 21:08

Allen


2 Answers

The example doesn't work because it assumes sqlbuddy is in the beginning of the string. You need to change it to the following, so that sqlbuddy can appear anywhere in the string:

^(?!.*sqlbuddy.*).*$ 

However, if you really just want to check if your string contains a given word, then maybe a "http://12.34.567.890/sqlbuddy".contains("sqlbuddy") will suffice.

like image 154
João Silva Avatar answered Nov 09 '22 00:11

João Silva


Also, this worked for me: Position of the string 'sqlbuddy' doesn't matter.

^((?!sqlbuddy).)*$

like image 40
Nick Radford Avatar answered Nov 09 '22 00:11

Nick Radford