简体   繁体   English

如何使用`re.sub()`替换部分str?

[英]How to replace part of str using `re.sub()`?

I can replace oldText with newText1 as re.sub("'(.*)'", 'newText', "test = 'oldText'") But I am trying to use re.sub() as re.sub("'test = (.*)'", 'newText', "test = 'oldText'") 我可以代替oldTextnewText1re.sub("'(.*)'", 'newText', "test = 'oldText'")但我想使用re.sub()re.sub("'test = (.*)'", 'newText', "test = 'oldText'")

Can I pass actual text in pattern? 我可以在模式中传递实际文本吗?

I think numbers were bad example I updated with str. 我认为数字是我用str更新的不好的例子。 The first one works but second one doesn't. 第一个有效,但第二个无效。 Isn't it allowed to have actual text in pattern? 不允许在模式中包含实际文本吗?

>>> import re
>>> 
>>> re.sub(r"(test = )'.*'", r"\1'" + str(22) + r"'", "test = '21'")
"test = '22'"

You can do it but you need to grab all the other parts of the match and piece it back together with the new result. 您可以做到,但是您需要抓住比赛的所有其他部分,并将其与新结果重新组合在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM