如何使用python regex替换使用捕获的组? [英] How to use python regex to replace using captured group?

查看:40
本文介绍了如何使用python regex替换使用捕获的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想把蓝狗和蓝猫戴蓝帽子改为灰狗和灰猫戴蓝帽子.

使用 sed 我可以按如下方式完成:

$ echo '蓝狗蓝猫戴蓝帽子' |sed 's/blue \(dog\|cat\)/gray \1/g'

如何在 Python 中进行类似的替换?我试过了:

<预><代码>>>>进口重新>>>s = "蓝狗和蓝猫戴着蓝帽子">>>p = re.compile(r"blue (dog|cat)")>>>p.sub('灰色\1',s)'灰色 \x01 和灰色 \x01 戴着蓝色帽子'

解决方案

你需要转义你的反斜杠:

p.sub('灰色 \\1', s)

或者,您可以像使用正则表达式一样使用原始字符串:

p.sub(r'gray \1', s)

Suppose I want to change the blue dog and blue cat wore blue hats to the gray dog and gray cat wore blue hats.

With sed I could accomplish this as follows:

$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'

How can I do a similar replacement in Python? I've tried:

>>> import re
>>> s = "the blue dog and blue cat wore blue hats"
>>> p = re.compile(r"blue (dog|cat)")
>>> p.sub('gray \1',s)
'the gray \x01 and gray \x01 wore blue hats'

解决方案

You need to escape your backslash:

p.sub('gray \\1', s)

alternatively you can use a raw string as you already did for the regex:

p.sub(r'gray \1', s)

这篇关于如何使用python regex替换使用捕获的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆