您的位置:首页 > 编程语言 > Python开发

Python 正则表达式 带分组的替换 \g<1> \g<2>

2013-06-06 21:49 836 查看
import re
p = re.compile(r'^(task_cnt\s)\S*\s\S$', re.M)
for i in range(0, 11):
filename = 'graph' + str(1000 + 100 * i) + '.tgffopt'
fp_o = open(filename, 'r')
all = fp_o.read()
fp_o.close
print all
fp_i = open(filename, 'w')
match = p.search(all)
print match.group(1)
fp_i.write(p.sub(r'\g<1>' + str(1000 + 100 * i) +' 0', all))
fp_i.close


此程序目的是将10个文件中task_cnt 500 3的内容替换为按文件名区分的task_cnt 1000 0(graph1000.tgff)、task_cnt 1100 0(graph1100.tgff)......

替换的并不是\g<1>代表的内容,而是替换了除了它之外的内容,见第12行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: