正则表达式:根据单词匹配/不匹配排除或包含匹配项

时间:2018-02-27 10:08:30

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

如果存在少量单词,我想匹配一个句子,如果存在某些其他单词则丢弃该匹配。

例如:

如果字符串有" consumer"我希望正则表达匹配发生。和"服务"如果字符串有单词"延迟"。

,则匹配不会发生

匹配发生:

"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)

2 个答案:

答案 0 :(得分: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'也会匹配)但是,无论如何,这可能是可取的。

答案 1 :(得分:0)

您可以使用否定前瞻:

▶ 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]