Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists.

patterns = [
    re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'),
    re.compile(r'
+|s{2}')
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
714 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use verbose mode to write more readable regular expressions. In this mode:

  • Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash.
  • When a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored.

The following two statements are equivalent:

a = re.compile(r"""d +  # the integral part
                   .    # the decimal point
                   d *  # some fractional digits""", re.X)

b = re.compile(r"d+.d*")

(Taken from the documentation of verbose mode)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...