是否有与 Perl 的“/x"等效的 Python?正则表达式的修饰符? [英] Is there a Python equivalent to the Perl "/x" modifier for regular expressions?

查看:65
本文介绍了是否有与 Perl 的“/x"等效的 Python?正则表达式的修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 可以使用 /x 修饰符轻松构建可读的正则表达式.此修饰符允许编写正则表达式字符串并忽略这些字符串中的所有空格.换句话说,正则表达式的逻辑部分可以用空格甚至回车分隔,具有很好的可读性.在 Python 中,我看到这样做的唯一方法是构造这样的正则表达式字符串,在中间步骤中从中删除空格,然后使用结果字符串进行匹配.有没有更优雅的方法来做到这一点?

Perl makes it easy to construct readable regular expressions using the /x modifier. This modifier allows to write regular expression strings and ignore all whitespaces in these strings. In other words, logical parts of the regular expression can be separated by whitespace or even carriage returns, allowing great readability. In Python, the only way I see of doing this is to construct such regular expression string, remove whitespace from it in an intermediate step, and then use the resulting string for matching. Is there a more elegant way of doing this?

推荐答案

是的,通过设置 re.X/re.VERBOSE 标志:

Yes, by setting the re.X / re.VERBOSE flag:

这个标志允许你编写看起来更好的正则表达式.模式中的空格会被忽略,除非在字符类中,或者前面有未转义的反斜杠,或者在诸如 *?(?: 之类的标记内(?P<...>.当一行包含一个 # 不在字符类中并且前面没有未转义的反斜杠时,从最左边开始的所有字符,例如 # 到行尾都被忽略.

This flag allows you to write regular expressions that look nicer. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.

这意味着以下两个匹配十进制数的正则表达式对象在功能上是相等的:

That means that the two following regular expression objects that match a decimal number are functionally equal:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")

这与 /x Perl 标志非常相似.

This is pretty much exactly like the /x Perl flag.

您可以在 (?x:...)(启用)和 (?-x:...)(?-x:...)(启用)和代码>(禁用)分组.

You can control the same flag in a subsection of your pattern within the (?x:...) (enable) and (?-x:...) (disable) groupings.

这篇关于是否有与 Perl 的“/x"等效的 Python?正则表达式的修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆