Python 使用正则表达式替换文件中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35688126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace string in file with using regular expressions
提问by Michal Vasko
How can I replace string in file with using regular expressions in Python, because I want to open a file in which I shoud replace strings for other string and we need to use Reg Expressions(Search and Replace).Can anyone help me? some example of opening file and using it with search and replace methode
如何使用 Python 中的正则表达式替换文件中的字符串,因为我想打开一个文件,我应该在其中替换其他字符串的字符串,我们需要使用 Reg 表达式(搜索和替换)。有人可以帮助我吗?打开文件并将其与搜索和替换方法一起使用的一些示例
回答by Quinn
# 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'--', content, flags = re.M)
回答by user2532296
Here is a general format, you can either use re.sub, re.match based on your requirement. Below is a general pattern for opening a file and doing it
这是一个通用格式,您可以根据您的要求使用 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)