【问题标题】:Match string that doesn't contain a specific word匹配不包含特定单词的字符串
【发布时间】:2012-07-24 03:11:52
【问题描述】:

我正在使用 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

我想匹配不包含单词dog的网址,所以应该匹配第一个和第二个

【问题讨论】:

  • 这个问题最好在发帖here 上搜索类似问题。

标签: ruby regex match


【解决方案1】:

只需使用负前瞻^(?!.*dog).*$

说明

  • ^ : 匹配行首
  • (?!.*dog) : 否定前瞻,检查单词 dog 是否不存在
  • .* :匹配所有内容(在这种情况下,换行符除外)
  • $ : 匹配行尾

Online demo

【讨论】:

  • 哇,这条信息出奇地难找。
【解决方案2】:

随便用

string !~ /dog/

选择你需要的字符串。

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 更简洁,array_of_urls.reject { |url| url.match(/dog/) }
    【解决方案4】:

    您可以使用的另一件事是:

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

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多