Python:如何使用长正则表达式进行行继续?

bor*_*cle 7 python regex

我有一个很长的正则表达式,我想继续到下一行,但我尝试的一切给了我一个EOL或打破正则表达式.我已经在括号内继续了一行,并阅读了这一点,除此之外,我如何在Python中进行换行(换行)?

工作,但仍然太长:

REGEX = re.compile(
            r'\d\s+\d+\s+([A-Z0-9-]+)\s+([0-9]+.\d\(\d\)[A-Z0-9]+)\s+([a-zA-Z\d-]+)')
Run Code Online (Sandbox Code Playgroud)

错误:

REGEX = re.compile(
            r'\d\s+\d+\s+([A-Z0-9-]+)\s+([0-9]+.\d\(\d\)[A-Z0-9]+
            )\s+([a-zA-Z\d-]+)')

SyntaxError: EOL while scanning string literal


REGEX = re.compile(
            r'\d\s+\d+\s+([A-Z0-9-]+)\s+([0-9]+.\d\(\d\
                )[A-Z0-9]+)\s+([a-zA-Z\d-]+)')

sre_constants.error: unbalanced parenthesis


REGEX = re.compile(
            r'\d\s+\d+\s+([A-Z0-9-]+)\s+( \
            [0-9]+.\d\(\d\)[A-Z0-9]+)\s+([a-zA-Z\d-]+)')

regex no longer works


REGEX = (re.compile(
            r'\d\s+\d+\s+([A-Z0-9-]+)\s+(
            [0-9]+.\d\(\d\)[A-Z0-9]+)\s+([a-zA-Z\d-]+)'))

SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)

我已经能够缩短我的正则表达式,所以这不再是一个问题,但我现在有兴趣知道如何使用长正则表达式进行行继续?

Mar*_*ans 12

如果您使用该re.VERBOSE标志,您可以根据需要将正则表达式拆分为更易读:

pattern = r"""
    \d\s+
    \d+\s+
    ([A-Z0-9-]+)\s+
    ([0-9]+.\d\(\d\)[A-Z0-9]+)\s+
    ([a-zA-Z\d-]+)"""

REGEX = re.compile(pattern, re.VERBOSE)
Run Code Online (Sandbox Code Playgroud)

这种方法在优秀的"Dive Into Python"一书中有所解释.
请参阅"详细正则表达式".


Ana*_*mar 5

您可以在多行中使用多个字符串,Python会在发送到之前将它们串联起来(只要多个字符串在(和之间)re.compile。范例-

REGEX = re.compile(r"\d\s+\d+\s+([A-Z0-9-]+)\s+([0-9]+.\d\(\d\)"
                   r"[A-Z0-9]+)\s+([a-zA-Z\d-]+)")
Run Code Online (Sandbox Code Playgroud)