9

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?

Allen
  • 1,903
  • 1
  • 22
  • 28

3 Answers3

6

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.

João Silva
  • 81,431
  • 26
  • 144
  • 151
  • Thank you. I'm using it with mod_rewrite so I can't use .contains(), but it works and so does the other answer below. However, for some reason it doesn't match using the regex tester at http://gskinner.com/RegExr/ – Allen Aug 03 '11 at 03:33
  • @Allen, check out rubular, it's what I use for my Regex testing, and I really like it. – Nick Radford Aug 03 '11 at 16:12
  • +1 but minor tweak: you don't need the `.*` after `sqlbuddy`. This is enough: `(?m)^(?!.*?sqlbuddy).*$` or `(?m)^(?!.*sqlbuddy).*$` depending on whether you want to go lazy or backtrack. – zx81 May 12 '14 at 02:59
2

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

^((?!sqlbuddy).)*$

Nick Radford
  • 970
  • 5
  • 13
0

...also (for other people), if you want to search only in a specific place of a [long] string (long text with multiple matches), you can use:

first_part_of_string(?!.*sqlbuddy.*)second_part_of_string

or, more permissive:

first_part_of_string.*(?!.*sqlbuddy.*).*second_part_of_string
XXN
  • 80
  • 9