26

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

sudo bangbang
  • 27,127
  • 11
  • 75
  • 77
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99
  • This question is best answered on posting [here](http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word) Searching SO for similar questions is a good idea. – Vaman Kulkarni Jul 25 '12 at 16:28

4 Answers4

52

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

HamZa
  • 14,671
  • 11
  • 54
  • 75
9

Just use

string !~ /dog/

to select strings you need.

nicholaides
  • 19,211
  • 12
  • 66
  • 82
Anton
  • 3,006
  • 3
  • 26
  • 37
2

There's actually an incredibly simple way to do this, using select.

array_of_urls.select { |url| !url.match(/dog/) }

this will return an array of the url's that don't contain the word 'dog' anywhere in it.

nfriend21
  • 2,170
  • 1
  • 21
  • 21
0

Another thing you can use is:

!url['dog']

With your example:

array = []
array << 'http://website1.com/url_with_some_words.html'
array << 'http://website2.com/url_with_some_other_words.html'
array << 'http://website3.com/url_with_the_word_dog.html'

array.select { |url| !url['dog'] }

You could also reject the urls that do contain 'dog':

array.reject { |url| url['dog'] }
Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55