【问题标题】:Regex: Exclude or include a match based on word match/not match [duplicate]正则表达式:根据单词匹配/不匹配排除或包含匹配项[重复]
【发布时间】:2018-08-06 22:41:39
【问题描述】:

如果出现的单词很少,我想匹配一个句子,如果出现某些其他单词,我想放弃匹配。

例如:

如果字符串包含“consumer”和“services”,我希望进行正则表达式匹配,如果字符串包含单词“delayed”,则不进行匹配。

比赛即将发生:

"Consumer are offered services based on the plans selected"

匹配不会发生:

"In case ,the consumer services are delayed then penalty shall be beared."

为匹配编写的正则表达式:

(\b(?:consumer)\b.*?services)

【问题讨论】:

  • 试试/^(?!.*\bdelayed\b)(?=.*\bconsumer\b)(?=.*\bservices\b)/

标签: ruby regex string-matching regex-negation regex-lookarounds


【解决方案1】:

你真的需要一个正则表达式吗?我认为没有代码会更容易理解:

input = 'Consumer are offered services based on the plans selected'

input_lower = input.downcase

input_lower.include?('consumer') &&
  input_lower.include?('services') &&
  !input_lower.include?('delayed')

这不是完全检查您所询问的内容,因为它不是在寻找单词边界(例如'Consumers' 也会匹配),但无论如何这可能是可取的。

【讨论】:

    【解决方案2】:

    您可以使用否定的前瞻:

    ▶ input = ["Consumer are offered services based on the plans selected",
    ▷   "In case ,the consumer services are delayed then penalty shall be beared."]  
    
    ▶ input.map { |line| line =~ /(?!.*delayed)(consumer|services)/ }
    #⇒ [21, nil]
    

    【讨论】:

    • 注意:如果字符串包含“consumer”“services”,我希望进行正则表达式匹配。顺便说一句,尾随 .* 是多余的。
    猜你喜欢
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多