Skip to main content
 首页 » 编程设计

python之如何使用正则表达式修改字符串的内容(就像 String.Replace)

2024年11月01日22luoye11

<分区>

我想在 python 中使用正则表达式替换字符串的内容。

我试过下面的代码:

regex=r"(?:ab*)\w+" 
text ="absd 2013 abpq ab 123absd" 
pattern=re.compile(regex) 
print pattern.sub("dummy",text) 

我得到这样的输出:

dummy 2013 dummy dummy 123dummy 

但我的实际文本仍然相同。

我可以用正则表达式修改文本本身吗?