首页 > 解决方案 > Python RE匹配不是左括号然后是字符串

问题描述

我想使用 python 匹配以下模式re.search

((不是左括号,然后是 1-3 个空格)或(字符串的开头))然后是(字符 1 或 E)然后是(任意数量的空格)然后是(右括号)。

这是我到目前为止所拥有的:

re.search(r'((^\(\s{1,3})|^)[1tE]\s+\)', text)

想匹配例子

text = "  E  )"
text = "1 )"

不想匹配示例

text = "( 1 )

标签: pythonregex

解决方案


考虑以下模式:

  • (
    • ( not open bracket, then 1-3 spaces)-[^(]\s{1,3}
    • or-|
    • (the start of the string)-^
  • )
  • (characters 1 or E)-[1E]
  • (any number of spaces)-\s*
  • (close bracket)- \)

将所有这些加入一个模式:

(?:[^(]\s{1,3}|^)[1E]\s*\)

要匹配整个字符串,请添加锚点,^然后$

^(?:[^(]\s{1,3}|^)[1E]\s*\)$

请参阅正则表达式演示

(?:...)是一个非捕获组,如果您将来需要访问它的值,请使用捕获组。

您可以使用详细的正则表达式表示法使其更具可读性和可维护性:

re.search(
    r"""
    (?:
        [^(]\s{1,3}  # not open bracket, then 1-3 spaces
        |            # or
        ^            # the start of the string
    )
    [1E]  # characters 1 or E
    \s*   # any number of spaces
    \)    # close bracket
    """,
    text,
    re.VERBOSE
)

推荐阅读