【问题标题】:Commenting Regular expressions in python在python中注释正则表达式
【发布时间】:2013-12-18 21:41:04
【问题描述】:

This answer 在关于正则表达式可维护性的问题中提到 .NET 用户在其正则表达式中实现 cmets 的能力(我对第二个示例特别感兴趣)

是否有一种简单的本地方法可以在 python 中重现这一点,最好无需安装第三方库或编写我自己的评论条算法?

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

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

【问题讨论】:

  • 是的,请参阅re 模块中的verbose flag
  • 使用named groups 也有助于提高正则表达式代码的可读性。

标签: python regex


【解决方案1】:

您正在re 模块中寻找@​​987654321@ 标志。其文档中的示例:

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

【讨论】:

  • 您也可以在正则表达式本身中指定此标志,方法是在开头放置(?x)
【解决方案2】:
r"""
(?:      # Match the regular expression below
   /        # Match the character “/” literally
   \*       # Match the character “*” literally
   \*       # Match the character “*” literally
)
"""

您也可以像这样将 cmets 添加到正则表达式中:

(?#The following regex matches /** in a non-capture group :D)(?:/\*\*)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-26
    • 2016-07-20
    • 2020-07-08
    • 1970-01-01
    • 2014-12-17
    • 2014-01-29
    • 2012-10-26
    • 2020-02-02
    相关资源
    最近更新 更多