Python 正则表达式条件,不匹配 if

Python regex conditional, don't match if

抱歉这个标题有点无用,我真的很难解释这个问题。

我有一个可以以多种不同方式出现的唯一标识符列表,我正在尝试使用正则表达式对其进行规范化,以便我可以跨多个数据库进行比较。以下是其中的一些示例:

AB1201
AB-1201
AB1201-T
AB-12-01L1
AB1201-TER
AB1201 Transit

我写了一行代码来提取所有连字符和空格,并使用了这个正则表达式:

([a-zA-Z]{2}[\d]{4})(L\d|Transit|T$)?

这完全符合预期,返回一个如下所示的列表:

AB1201
AB1201
AB1201T
AB1201L1
AB1201
AB1201T

问题是,我有一个如下所示的标识符:AB1201-02。我需要将其作为例外提出,而不是作为匹配项包括在内。

有什么想法吗?如有必要,我很乐意提供更多说明。谢谢!

From Regex101 online tester

试试这个正则表达式

^([a-zA-Z]{2}[\d]{4})(?!-\d)(L\d|Transit|T|-[A-Z]{3})?$

我添加了 (?!...) Negative Lookahead 以避免与 -02 匹配。

(?!...) Negative Lookahead: Starting at the current position in the expression, ensures that the given pattern will not match. Does not consume characters.

您可以在 this link 上观看演示。

您可以使用否定先行排除匹配以下连字符和数字 (?!-\d)

如果它应该从字符串的开头开始,您可以使用锚点 ^

请注意,您可以将 [\d] 写为 \d

^([a-zA-Z]{2}\d{4})(?!-\d)(L\d|Transit|T$)?

图案看起来像

  • ^ 字符串开头
  • ( 捕获 组 1
    • [a-zA-Z]{2}\d{4}匹配2次a-zA-Z和4位数字
  • ) 关闭群组
  • (?!-\d) 负前瞻,断言直接在右边的不是-和数字
  • (L\d|Transit|T$)? 可选捕获 组 2

Regex demo