Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting Regular expressions in python

Tags:

python

regex

This answer to a question regarding the maintainability of regular expressions mentions the ability of .NET users to implement comments in their regular expressions (I am particularly interested in the second example)

Is there an easy native way to reproduce this in python, preferably without having to install a third party library or writing my own comment-strip algorithm?

what I currently do is similar to the first example in that answer, I concatenate the regular expression in multiple lines and comment each line, like in the following example:

    regexString  =  '(?:' # Non-capturing group matching the beginning of a comment
    regexString +=      '/\*\*'
    regexString +=  ')'
like image 731
DudeOnRock Avatar asked Dec 15 '22 03:12

DudeOnRock


2 Answers

You're looking for the VERBOSE flag in the re module. Example from its documentation:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
like image 112
Wieland Avatar answered Dec 23 '22 09:12

Wieland


r"""
(?:      # Match the regular expression below
   /        # Match the character “/” literally
   \*       # Match the character “*” literally
   \*       # Match the character “*” literally
)
"""

You can also add comments into regex like this:

(?#The following regex matches /** in a non-capture group :D)(?:/\*\*)

like image 31
Vasili Syrakis Avatar answered Dec 23 '22 08:12

Vasili Syrakis