【问题标题】:combining negation to and with other expressions将否定与其他表达式结合起来
【发布时间】: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


【解决方案1】:

否定前瞻的非捕获组肯定提供了您正在寻找的 AND 功能,因此您可以通过以下方式扩展该推理:

^(?!.*(hello|world))(?!.*(foo.*foo|bar.*bar)).*foo.*bar.*$

此外,应用德摩根定律之一(将交替视为 OR)让我们将规则 2 和 3 合并为一组

^(?!.*(hello|world|foo.*foo|bar.*bar)).*foo.*bar.*$

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2015-02-17
    • 1970-01-01
    • 2019-12-27
    • 2018-06-21
    • 2018-07-12
    相关资源
    最近更新 更多