【发布时间】:2010-10-31 19:49:18
【问题描述】:
有没有一种更简洁的方法可以在 python 中编写长正则表达式模式?我在某处看到了这种方法,但 python 中的正则表达式不允许列表。
patterns = [
re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'),
re.compile(r'\n+|\s{2}')
]
【问题讨论】:
有没有一种更简洁的方法可以在 python 中编写长正则表达式模式?我在某处看到了这种方法,但 python 中的正则表达式不允许列表。
patterns = [
re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'),
re.compile(r'\n+|\s{2}')
]
【问题讨论】:
您可以使用详细模式来编写更具可读性的正则表达式。在这种模式下:
以下两个语句是等价的:
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
(取自verbose mode的文档)
【讨论】:
虽然@Ayman 关于re.VERBOSE 的建议是一个更好的主意,但如果你想要的只是你所展示的,那就去做吧:
patterns = re.compile(
r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'
r'\n+|\s{2}'
)
而 Python 的相邻字符串文字的自动连接(很像 C 语言,顺便说一句)将完成剩下的工作;-)。
【讨论】:
您可以在正则表达式中使用 cmets,这使它们更具可读性。以http://gnosis.cx/publish/programming/regular_expressions.html为例:
/ # identify URLs within a text file
[^="] # do not match URLs in IMG tags like:
# <img src="http://mysite.com/mypic.png">
http|ftp|gopher # make sure we find a resource type
:\/\/ # ...needs to be followed by colon-slash-slash
[^ \n\r]+ # stuff other than space, newline, tab is in URL
(?=[\s\.,]) # assert: followed by whitespace/period/comma
/
【讨论】: