【发布时间】:2019-08-16 22:15:18
【问题描述】:
我正在尝试将几个正则表达式与“and”结合起来。我让每个单独的正则表达式都在工作,但我不确定如何将它们组合在一起,以使最终结果将每个表达式“和”在一起。
我正在尝试
1) check for a sequence of certain words.
2) check to see if certain words appear at most once
3) check for absence of certain words (using negation)
举个例子,想完成这三个:
1) check if "foo" precedes "bar" in the string
2) check to see if "foo" and "bar" each appear only once
3) check to see if "hello" and "world" do NOT appear
此字符串应匹配:"foo hi bar",但 "foo hello bar" 不应匹配,"foo foo bar" 也不应匹配。
对于 (1) 和 (2) 我可以使用:
^(?!(.*\bfoo\b.*\bfoo\b)|(.*\bbar\b.*\bbar\b)).*\bfoo\b.*\bbar\b.*$
成功了。
对于 (3) 我可以使用前瞻:
^((?!\bhello|\bworld).)*$
成功了。
但是,我不知道如何将 (1) 和 (2) 和 (3) 组合在一起。
我曾尝试使用(?=pattern)(?=pattern) 作为与-ing 的一种方式,但没有成功:
^(?=(?!(.*\bfoo\b.*\bfoo\b)|(.*\bbar\b.*\bbar\b)).*\bfoo\b.*\bbar\b.*)(?=((?!\bhello|\bworld).))*$
【问题讨论】:
-
我认为 $ 之前的最后一个 * 应该在最后一个右括号之前
标签: regex regex-negation regex-group