Perl 使构造 readable regular expressions 变得容易使用 /x
修饰符。此修饰符允许编写正则表达式字符串并忽略这些字符串中的所有空格。换句话说,正则表达式的逻辑部分可以用空格甚至回车分隔,从而提高可读性。在 Python 中,我看到这样做的唯一方法是构造这样的正则表达式字符串,在中间步骤中从中删除空格,然后使用生成的字符串进行匹配。有更优雅的方法吗?
最佳答案
是的,通过设置 re.X
/ re.VERBOSE
flag :
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 标志。
您可以在 (?x:...)
中的模式的一个小节中控制相同的标志。 (启用)和 (?-x:...)
(禁用)分组。
关于python - 是否有与正则表达式的 Perl "/x"修饰符等效的 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316433/