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

Victor Hooi victorhooi at gmail.com
Tue Apr 16 19:45:20 EDT 2013


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



More information about the Python-list mailing list