Ruby 正则表达式:基于单词匹配/不匹配排除或包括匹配
如果没有几个单词,我想匹配一个句子;如果有其他单词,我想放弃匹配 例如: 如果字符串有“consumer”和“services”,我希望正则表达式匹配发生;如果字符串有单词“delayed”,则不希望匹配发生 将要发生的匹配:Ruby 正则表达式:基于单词匹配/不匹配排除或包括匹配,ruby,regex,string-matching,regex-negation,regex-lookarounds,Ruby,Regex,String Matching,Regex Negation,Regex Lookarounds,如果没有几个单词,我想匹配一个句子;如果有其他单词,我想放弃匹配 例如: 如果字符串有“consumer”和“services”,我希望正则表达式匹配发生;如果字符串有单词“delayed”,则不希望匹配发生 将要发生的匹配: "Consumer are offered services based on the plans selected" "In case ,the consumer services are delayed then penalty shall be beared."
"Consumer are offered services based on the plans selected"
"In case ,the consumer services are delayed then penalty shall be beared."
不发生匹配:
"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)
您可以使用负前瞻:
▶ 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]
你真的需要一个正则表达式吗?我认为如果没有代码,代码将更容易理解:
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')
这并不是完全检查您所问的内容,因为它不查找单词边界(例如,“消费者”
也会匹配),但这可能是可取的。尝试/^(?。*\b显示\b)(?=.*\b消费者\b)(?=.*\b服务\b)/
注意:如果字符串有“消费者”和“服务”,我希望正则表达式匹配。顺便说一句,尾随的*
是冗余的。