如何在Python中使用正则表达式替换文件中的字符串,因为我想打开一个文件,其中我应该替换其他字符串的字符串,我们需要使用Reg表达式(搜索和替换)。任何人都可以帮助我?打开文件并将其与搜索和替换方法一起使用的一些示例
答案 0 :(得分:12)
# The following code will search 'mm/dd/yyyy' (e.g. NOV/30/2016 ),
# 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('(\w{2})/(\d{2})/(\d{4})', r'\1-\2-\3', content, flags = re.M)
答案 1 :(得分:-1)
这是一般格式,你可以根据你的要求使用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)