不包含特定单词的字符串匹配

27

我正在使用 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应该被匹配。


这个问题最好在这里发布[https://dev59.com/4nRC5IYBdhLWcg3wG9To]。在SO上搜索类似的问题是一个好主意。 - Vaman Kulkarni
4个回答

53

只需使用负向先行断言 ^(?!.*dog).*$

解释

  • ^ :匹配行首
  • (?!.*dog):负向先行断言,检查单词“dog”是否不存在
  • .*:匹配所有内容(在此情况下除了换行符)
  • $:匹配行尾

在线演示


1
哇,这条信息竟然很难找到。 - B Seven

9

只需使用

string !~ /dog/

选择字符串需要使用以下方法。


2

实际上,使用选择器(select)有一种非常简单的方法可以做到这一点。

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

这将返回一个URL数组,其中不包含单词“dog”。


1
更简洁地说,array_of_urls.reject { |url| url.match(/dog/) } - nicholaides

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' 的url:

array.reject { |url| url['dog'] }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接