假设我想将the blue dog and blue cat wore blue hats
更改为the gray dog and gray cat wore blue hats
。
有了sed
我可以做到如下:
$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'
如何在Python中进行类似的替换?我试过:
>>> 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'
你需要避开你的反斜杠:
或者,也可以像对regex所做的那样使用原始字符串:
我在寻找一个类似的答案;但是想要在replace中使用命名组,我想我应该为其他人添加代码:
试试这个:
相关问题 更多 >
编程相关推荐