Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string that doesn't contain a specific word

Tags:

regex

ruby

match

I'm working with ruby with the match method and I want to match an URL that doesn't contain a certain string with a regular Expression: ex:

http://website1.com/url_with_some_words.html http://website2.com/url_with_some_other_words.html http://website3.com/url_with_the_word_dog.html 

I want to match the URLs that doesn't contain the word dog, so the 1st and the 2nd ones should be matched

like image 559
Ghilas BELHADJ Avatar asked Jul 25 '12 16:07

Ghilas BELHADJ


2 Answers

Just use a negative lookahead ^(?!.*dog).*$.

Explanation

  • ^ : match begin of line
  • (?!.*dog) : negative lookahead, check if the word dog doesn't exist
  • .* : match everything (except newlines in this case)
  • $ : match end of line

Online demo

like image 189
HamZa Avatar answered Oct 03 '22 09:10

HamZa


Just use

string !~ /dog/ 

to select strings you need.

like image 35
Anton Avatar answered Oct 03 '22 07:10

Anton