首页 > 解决方案 > 使用正则表达式替换文件中的子字符串和python

问题描述

假设我有一个带有
aaaa = /bbb/ccc/ddd/eee/fff 行的 file.txt

我想用 xxx 替换 ccc

我尝试了下一个但没有成功

import re
import fileinput

for line in fileinput.input(file.txt, inplace=True):
    re.sub(r'(ccc)', 'xxx', line)

标签: python

解决方案


尝试这个:


m = re.sub(r'ccc', r'xxx', "/bbb/ccc/ddd/eee/fff")
#OUTPUT: /bbb/xxx/ddd/eee/fff

推荐阅读