Skip to main content
 首页 » 编程设计

c#之正则表达式之增量替换

2024年01月13日49JustinYoung

有没有办法只用正则表达式进行整数增量替换。

这是问题所在,我的文本文件包含 1 000 000 行,全部以 % 开头

我想使用正则表达式逐步将 # 替换为整数。

input: 
 
% line one 
 
% line two 
 
% line three 
 
... 
 
output: 
 
1 line one 
 
2 line two 
 
3 line three 
 
... 

请您参考如下方法:

n = 1 
with open('sourcefile.txt') as input: 
    with open('destination.txt', 'w') as output: 
        for line in input: 
            if line.startswith('%'): 
                line = str(n) + line[1:] 
                n += 1 
            output.write(line)