清理Python正则表达式 [英] Clean Python Regular Expressions
本文介绍了清理Python正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种更干净的方式在python中编写长的regex模式?我在某处看到了这种方法,但是python中的正则表达式不允许使用列表.
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'\n+|\s{2}')
]
推荐答案
您可以使用详细模式来编写更具可读性的正则表达式.在这种模式下:
You can use verbose mode to write more readable regular expressions. In this mode:
- 模式中的空格将被忽略,除非是在字符类中或在其前加上未转义的反斜杠.
- 当某行中的字符类中都没有包含#"时,或者在其前面没有未转义的反斜杠时,从最左边的#"到行尾的所有字符都将被忽略.
以下两个语句是等效的:
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*")
(摘录自详细模式的文档)
这篇关于清理Python正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文