我正在使用 Ruby 的 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个URL应该被匹配。
我正在使用 Ruby 的 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个URL应该被匹配。
只需使用负向先行断言 ^(?!.*dog).*$
。
解释
^
:匹配行首(?!.*dog)
:负向先行断言,检查单词“dog”是否不存在.*
:匹配所有内容(在此情况下除了换行符)$
:匹配行尾只需使用
string !~ /dog/
选择字符串需要使用以下方法。
实际上,使用选择器(select)有一种非常简单的方法可以做到这一点。
array_of_urls.select { |url| !url.match(/dog/) }
这将返回一个URL数组,其中不包含单词“dog”。
array_of_urls.reject { |url| url.match(/dog/) }
- nicholaides你还可以使用另外一种方法:
!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'
的url:
array.reject { |url| url['dog'] }