【问题标题】:How to use a special sequence in substitute pattern in re.sub [duplicate]如何在 re.sub 的替代模式中使用特殊序列 [重复]
【发布时间】:2017-04-07 16:10:24
【问题描述】:

我有一个字符串,我想将每个[ 替换为[[]] 替换为[]](同时)。我考虑过使用re.sub

re.sub(r'(\[|\])', '[\1]', 'asdfas[adsfasd]')
Out: 'asdfas[\x01]adsfasd[\x01]'

但是我没有得到想要的结果——如何让re.sub 将模式中的\1 视为第一个匹配的特殊组?

【问题讨论】:

  • re.sub(r'(\[|\])', r'[\1]', 'asdfas[adsfasd]')

标签: python regex substitution


【解决方案1】:

您也应该为替换正则表达式使用 r 前缀,否则 \1 将被解释为十六进制文字:

In [125]: re.sub(r'(\[|\])', r'[\1]', 'asdfas[adsfasd]')

Out[125]: 'asdfas[[]adsfasd[]]'

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多