在python中评论正则表达式

Dud*_*ock 3 python regex

这个关于正则表达式可维护性问题的答案提到了.NET用户在正则表达式中实现注释的能力(我对第二个例子特别感兴趣)

有没有一种简单的原生方式在python中重现这个,最好不需要安装第三方库或编写我自己的注释条算法?

我目前所做的与该答案中的第一个示例类似,我将多个行中的正则表达式连接起来并对每一行进行注释,如下例所示:

    regexString  =  '(?:' # Non-capturing group matching the beginning of a comment
    regexString +=      '/\*\*'
    regexString +=  ')'
Run Code Online (Sandbox Code Playgroud)

Wie*_*and 8

您正在寻找模块中的VERBOSE标志re.其文档中的示例:

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

  • 您也可以在正则表达式中指定此标志,方法是在开头添加`(?x)`. (4认同)