DudeOnRock
DudeOnRock

Reputation: 3831

Commenting Regular expressions in python

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 +=  ')'

Upvotes: 10

Views: 5727

Answers (2)

Vasili Syrakis
Vasili Syrakis

Reputation: 9591

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)(?:/\*\*)

Upvotes: 4

Wieland
Wieland

Reputation: 1681

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)

Upvotes: 18

Related Questions