我正在使用该match方法使用 ruby,并且我想将不包含特定字符串的 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
我想匹配不包含 word 的 URL dog,所以应该匹配第一个和第二个
只需使用负前瞻^(?!.*dog).*$。
解释
^: 匹配行首(?!.*dog): 否定前瞻,检查单词 dog 是否不存在.*:匹配所有内容(在这种情况下,换行符除外)$: 匹配行尾只需使用
string !~ /dog/
选择您需要的字符串。
实际上有一种非常简单的方法可以做到这一点,使用 select。
array_of_urls.select { |url| !url.match(/dog/) }
这将返回一个 url 的数组,其中不包含单词“dog”。
您可以使用的另一件事是:
!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'] }