python - 是否有与正则表达式的 Perl "/x"修饰符等效的 Python?

标签 python regex perl

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/

相关文章:

mysql - 将 perl 与 mysql 连接时,用户 'root' @'localhost'(使用密码 yes)的访问被拒绝

perl - 在 Perl 的 AnyEvent 下使用哪个日志记录模块?

python - 如何在 Qt Creator 中锚定小部件?

python - "coding: pyxl"在 Python 中如何工作?

python - 无法使用 Mixin 类扩展 python IntEnum

仅包含 [a-zA-Z0-9.-_] 且最大长度为 20 且不能以 '.' 结尾且最多只能包含两个 '.' 的字符串的正则表达式语法

regex - 为什么 RewriteRule .和 ^(.*)$ 一样吗?

ruby - 使用正则表达式从 Ruby 中的字符串中提取子字符串

perl - 为什么Perl函数 "map"给出错误 "Not enough arguments for map"

python - 如何在使用append()时避免for循环