python re.X vs automagic line延续(python re.X vs automagic line continuation)

编程入门 行业动态 更新时间:2024-10-23 23:23:12
python re.X vs automagic line延续(python re.X vs automagic line continuation)

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.

更多推荐

本文发布于:2023-07-15 05:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:automagic   python   continuation   line

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!