Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...