2012-07-25 59 views
22

我用的match方法红宝石工作,我想匹配不包含使用正则表达式某些字符串的URL: 例如:匹配字符串不包含特定单词

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 

我想匹配,不包含单词dog的URL,所以第1和第2者亦宜

+0

这个问题发布[这里](http://stackoverflow.com/questions/406230 /正则表达式匹配字符串不包含单词)搜索类似的问题是一个好主意。 – 2012-07-25 16:28:45

回答

34

只需使用负向预测^(?!.*dog).*$

说明

  • ^:匹配开始行
  • (?!.*dog):负先行,检查单词的狗不存在
  • .*:(在这种情况下,除了新行)匹配一切
  • $:匹配行尾

Online demo

+0

哇,这条信息令人惊讶地很难找到。 – 2015-10-26 22:07:29

7

只需使用

string !~ /dog/ 

选择你需要的字符串。

2

实际上,有一个非常简单的方法来做到这一点,使用选择。

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

这将返回一个网址的数组,其中任何地方都不包含单词'dog'。

+1

更简洁地说,'array_of_urls.reject {| url | url.match(/ dog /)}' – nicholaides 2014-11-28 19:12:03

+0

“令人难以置信的简单” – ahnbizcad 2015-03-12 05:20:31

0

可以使用的另一件事是:

!url['dog'] 

你的榜样:

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'] } 

你也可以拒绝该网址包含'dog'

array.reject { |url| url['dog'] } 
相关问题