如何使用Python中的正则表达式替换文件中的字符串?
我想打开一个文件,将其中的某些字符串替换为其他字符串,并且我们需要使用正则表达式进行搜索和替换。有什么打开文件并使用搜索和替换方法的示例可以参考吗?
# The following code will search 'MM/DD/YYYY' (e.g. 11/30/2016 or NOV/30/2016, etc ),
# and replace with 'MM-DD-YYYY' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
content = f.read()
content_new = re.sub('(\d{2}|[a-yA-Y]{3})\/(\d{2})\/(\d{4})', r'\1-\2-\3', content, flags = re.M)
r
没有区别。有一个线程,你可以查看一下:https://dev59.com/LWsz5IYBdhLWcg3wBzfi - Quinnre.sub
不是用于直接替换原文本的方法,如果想将新内容保存到文件中,需要进行额外的步骤。 - Quinn这是一个通用的格式。根据您的要求,您可以使用re.sub或re.match。以下是打开文件并执行操作的通用模式:
import re
input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0
for line in input_file:
match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression
if match_br:
br = match_br.group(1)
# Do something
elif match_ot:
ot = match_ot.group(2)
# Do your replacement
else:
output_file.write(line)
re.sub
。 - L3viathan