【问题标题】:Python regex match, but exclude if regex matchPython 正则表达式匹配,但如果正则表达式匹配则排除
【发布时间】:2022-12-11 16:55:39
【问题描述】:

我正在尝试为 re.search 编写一个正则表达式,它可以匹配一个字符串,只要单词“prod”存在于文本 (.产品。).但是,如果字符串中的任何位置都包含“orange”一词,则匹配失败。

web-prod-green # 应该匹配 web-prod-orange # 应该匹配失败 web-orange-green # 应该匹配失败 orange-prod-green # 应该匹配失败

我怎样才能做到这一点?

谢谢。

【问题讨论】:

  • 为什么要使用正则表达式?为什么不只是if "prod" in text and "orange" not in text?

标签: python


【解决方案1】:

我们可以使用否定前瞻来排除 orange 的存在:

^(?!.*orange).*prod.*$

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多