Python:如何使用长正则表达式进行换行? [英] Python: How do I do line continuation with a long regex?

查看:25
本文介绍了Python:如何使用长正则表达式进行换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的正则表达式,我想继续到下一行,但是我尝试过的所有操作都给了我一个 EOL 或破坏了正则表达式.我已经在括号内继续该行一次,并阅读了此内容,其中包括 如何在 Python 中进行换行(换行)?

I have a long regex that I want to continue on to the next line, but everything I've tried gives me either an EOL or breaks the regex. I have already continued the line once within the parenthesis, and have read this, among other things, 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

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

I have been able to shorten my regex so that this is no longer an issue, but I'm now interested to know how I might do line continuation with a long regex?

推荐答案

如果您使用 re.VERBOSE 标志,您可以随意拆分正则表达式以使其更具可读性:

If you use the re.VERBOSE flag, you can split your regular expression up as much as you like to make it more readable:

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)

这种方法在优秀的深入 Python"一书中进行了解释.
请参阅详细正则表达式".

This approach is explained in the excellent "Dive Into Python" book.
See "Verbose Regular Expressions".

这篇关于Python:如何使用长正则表达式进行换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆