【问题标题】:Formatting regex strings causes regex pattern characters to be escaped [duplicate]格式化正则表达式字符串会导致正则表达式模式字符被转义[重复]
【发布时间】:2019-11-21 03:29:06
【问题描述】:

我想将一些变量放入一个正则表达式中,同时也保持一个正则表达式模式。

regex = 'set groups {group} routing-instances (?P<routing_instances>[\w\W]+) interface {logical_interface}'.format(
        group=group,
        logical_interface=logical_interface
    )

但是,它会转义转义字符:

ipdb> regex                                                                                                                                             
'set groups GROUP1 routing-instances (?P<routing_instances>[\\w\\W]+) interface a10.555'

【问题讨论】:

  • 尝试在你的字符串前加上 r''

标签: python regex python-3.x


【解决方案1】:

使用原始字符串:

regex = r'your \regex \here'

另外,这并不重要,因为您的字符串实际上并不包含双斜杠,而是包含它们的 文本表示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2015-11-28
    • 2010-09-21
    相关资源
    最近更新 更多