使用编译对象的 Python regex sub

Chr*_*son 4 python regex

我有一个正则表达式<type '_sre.SRE_Pattern'>,我想用另一个字符串替换匹配的字符串。这是我所拥有的:

compiled = re.compile(r'some regex expression')
s = 'some regex expression plus some other stuff'
compiled.sub('substitute', s)
print(s)
Run Code Online (Sandbox Code Playgroud)

并且s应该是

'substitute plus some other stuff'
Run Code Online (Sandbox Code Playgroud)

但是,我的代码不起作用并且字符串没有改变。

cs9*_*s95 5

re.sub不是就地操作。从文档:

返回通过替换 repl 替换 string 中最左边的不重叠模式出现的字符串。

因此,您必须将返回值分配回a.

...
s = compiled.sub('substitute', s)
print(s)
Run Code Online (Sandbox Code Playgroud)

这给

'substitute plus some other stuff'
Run Code Online (Sandbox Code Playgroud)

正如你所期望的。