我有一个很长的正则表达式,我想继续下一行,但我尝试过的所有内容都给了我一个EOL或打破了正则表达式。我已经在括号内继续了一行,并阅读了这一内容,其中包括How can I do a line break (line continuation) in 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-]+)')
错:
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
我已经能够缩短我的正则表达式,所以这不再是一个问题,但我现在有兴趣知道如何使用长正则表达式继续行?
答案 0 :(得分:9)
如果您使用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)
这种方法在优秀的“Dive Into Python”一书中有所解释 请参阅“详细正则表达式”。
答案 1 :(得分:4)
您可以在多行中使用多个字符串,并且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-]+)")
答案 2 :(得分:3)
尝试:
regex = re.compile(
r'\d\s+\d+\s+([A-Z0-9-]+)\s+('
r'[0-9]+.\d\(\d\)[A-Z0-9]+)\s+([a-zA-Z\d-]+)'
)