1 import re 2 p = re.compile(r'^(task_cnt\s)\S*\s\S$', re.M) 3 for i in range(0, 11): 4 filename = 'graph' + str(1000 + 100 * i) + '.tgffopt' 5 fp_o = open(filename, 'r') 6 all = fp_o.read() 7 fp_o.close 8 print all 9 fp_i = open(filename, 'w') 10 match = p.search(all) 11 print match.group(1) 12 fp_i.write(p.sub(r'\g<1>' + str(1000 + 100 * i) +' 0', all)) 13 fp_i.close
此程序目的是将10个文件中task_cnt 500 3的内容替换为按文件名区分的task_cnt 1000 0(graph1000.tgff)、task_cnt 1100 0(graph1100.tgff)......
替换的并不是\g<1>代表的内容,而是替换了除了它之外的内容,见第12行。