如何在 re.sub 中的替换模式中使用特殊序列

How to use a special sequence in substitute pattern in re.sub

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

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

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

您还应该为替换正则表达式使用 r 前缀,否则 </code> 将被解释为十六进制文字:</p> <pre><code>In [125]: re.sub(r'(\[|\])', r'[]', 'asdfas[adsfasd]') Out[125]: 'asdfas[[]adsfasd[]]'