Python: How to make line continuation with a long regular expression?

I have a long regex that I want to continue on the next line, but everything I tried gives me either EOL or breaks the regex. I already continued the line once in parenthesis and read this, among other things, How to make a line break (line continuation) in Python?

It works, but still too long:

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

Wrong:

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 managed to shorten my regex, so this is no longer a problem, but now Iā€™m interested in knowing how I can continue a line with a long regex?

+4
source share
3 answers

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 - .

+6

, 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-]+)")
+4

to try:

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-]+)'
)
+3
source

Source: https://habr.com/ru/post/1612217/


All Articles