考虑一个基本的正则表达式,如 a(.+?)a
。如何用第一组的内容替换文件中出现的所有该正则表达式?
最佳答案
使用可以使用 re
模块在 python 中使用正则表达式和 fileinput
模块简单地就地替换文件中的文本
示例:
import fileinput
import re
fn = "test.txt" # your filename
r = re.compile('a(.+?)a')
for line in fileinput.input(fn, inplace=True):
match = r.match(line)
print match.group() if match else line.replace('\n', '')
之前:
hello this
aShouldBeAMatch!!!!! and this should be gone
you know
之后:
hello this
aShouldBeAMa
you know
注意:这是有效的,因为参数 inplace=True
导致输入文件被移动到备份文件并且标准输出被定向到输入文件,如 documented under Optional in-place filtering 。
关于python - 替换文件中的所有正则表达式匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11898054/