Python提供了一个标志( re.X或re.VERBOSE )来允许注释正则表达式:
a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X)但是,对于自动字符串连接,您可以实现基本相同的任务:
a = re.compile(r'\d+' # integral part r'\.' # decimal point r'\d*' # optional fractional digits )我不认为我真的看到过使用后一种形式,但(恕我直言)它使一个更容易阅读正则表达式(我不需要试图找出哪些空格已经逃脱,什么空白正在被忽略...等等),我的评论被我的文本编辑器格式化为评论。 有没有理由偏好前者而不是后者或签证诗? 或者这真的是番茄番茄问题?
Python provides a flag (re.X or re.VERBOSE) to allow annotation of regular expressions:
a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X)However, with automatic string concatenation, you could achieve basically the same thing:
a = re.compile(r'\d+' # integral part r'\.' # decimal point r'\d*' # optional fractional digits )I don't think that I've really seen the latter form used, but (IMHO) it makes for an easier to read regex (I don't need to try to figure out which whitespace has been escaped, and what whitespace is being ignored... etc. etc.) and my comments get formatted by my text editor as comments. Is there a reason to prefer the former over the latter or visa-verse? Or is this really a tomato-Tomato issue?
最满意答案
前者可以放在它自己的文本文件中,然后在不诉诸literal_eval情况下加载。 使用复杂的RE(或选择多个不同的RE),这可能是一个好处。
The former can be put in a text file of its own and then loaded without resort to literal_eval. With complicated REs (or a choice of multiple different REs), that may be a benefit.
更多推荐
发布评论