10

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 +=  ')'
2
  • 9
    Yes, see the verbose flag in the re module. Commented Dec 18, 2013 at 21:42
  • 2
    Using named groups can also help in the readability of your regex code. Commented Dec 18, 2013 at 21:53

2 Answers 2

18

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)
Sign up to request clarification or add additional context in comments.

1 Comment

You can also specify this flag in the regex itself by putting (?x) at the beginning.
5
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)(?:/\*\*)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.