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

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

regex - Clean Python Regular Expressions

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

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

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...