将否定与其他表达式结合起来
combining negation to and with other expressions
我正在尝试将几个正则表达式与 "and" 结合起来。我有每个单独的正则表达式工作,但我不确定如何将它们组合在一起,最终结果 "ands" 每个表达式在一起。
我正在尝试
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).))*$
负前瞻的非捕获组肯定会提供您正在寻找的 AND 功能,因此这是您可以扩展该推理的一种方法:
^(?!.*(hello|world))(?!.*(foo.*foo|bar.*bar)).*foo.*bar.*$
此外,应用 DeMorgan 定律之一(将交替视为 OR)让我们将规则 2 和 3 合并为一组
^(?!.*(hello|world|foo.*foo|bar.*bar)).*foo.*bar.*$
我正在尝试将几个正则表达式与 "and" 结合起来。我有每个单独的正则表达式工作,但我不确定如何将它们组合在一起,最终结果 "ands" 每个表达式在一起。
我正在尝试
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).))*$
负前瞻的非捕获组肯定会提供您正在寻找的 AND 功能,因此这是您可以扩展该推理的一种方法:
^(?!.*(hello|world))(?!.*(foo.*foo|bar.*bar)).*foo.*bar.*$
此外,应用 DeMorgan 定律之一(将交替视为 OR)让我们将规则 2 和 3 合并为一组
^(?!.*(hello|world|foo.*foo|bar.*bar)).*foo.*bar.*$