Using re.VERBOSE, and re-using components of regex?

V

Victor Hooi

Hi,

I'm trying to compile a regex Python with the re.VERBOSE flag (so that I can add some friendly comments).

However, the issue is, I normally use constants to define re-usable bits of the regex - however, these doesn't get interpreted inside the triple quotes.

For example:

import re

TIMESTAMP = r'(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{9})'
SPACE = r' '
FOO = r'some_regex'
BAR = r'some_regex'

regexes = {
'data_sent': re.compile("""
TIMESTAMP # Timestamp of our log message
SPACE
FOO # Some comment
SPACE
""", re.VERBOSE),
'data_received': re.compile("""
TIMESTAMP # Timestamp of our log message
SPACE
BAR # Some comment
SPACE
""", re.VERBOSE),
}

Is there a way to use CONSTANTS (or at least re-use fragments of my regex), and also use re.VERBOSE so I can comment my regex?

Cheers,
Victor
 
M

MRAB

Hi,

I'm trying to compile a regex Python with the re.VERBOSE flag (so that I can add some friendly comments).

However, the issue is, I normally use constants to define re-usable bits of the regex - however, these doesn't get interpreted inside the triple quotes.

For example:

import re

TIMESTAMP = r'(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{9})'
SPACE = r' '
FOO = r'some_regex'
BAR = r'some_regex'

regexes = {
'data_sent': re.compile("""
TIMESTAMP # Timestamp of our log message
SPACE
FOO # Some comment
SPACE
""", re.VERBOSE),
'data_received': re.compile("""
TIMESTAMP # Timestamp of our log message
SPACE
BAR # Some comment
SPACE
""", re.VERBOSE),
}

Is there a way to use CONSTANTS (or at least re-use fragments of my regex), and also use re.VERBOSE so I can comment my regex?
You could do it like this:

import re

constants = {}
constants['TIMESTAMP'] = r'(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{9})'
constants['SPACE'] = r'\ ' # Escape the space because it'll be in a
VERBOSE regex.
constants['FOO'] = r'some_regex'
constants['BAR'] = r'some_regex'

regexes = {
'data_sent': re.compile("""
{TIMESTAMP} # Timestamp of our
log message
{SPACE}
{FOO} # Some comment
{SPACE}
""".format(**constants), re.VERBOSE),
'data_received': re.compile("""
{TIMESTAMP} # Timestamp of our
log message
{SPACE}
{BAR} # Some comment
{SPACE}
""".format(**constants), re.VERBOSE),
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top