首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用正则表达式替换文件中的字符串

使用正则表达式替换文件中的字符串
EN

Stack Overflow用户
提问于 2016-02-28 20:52:36
回答 2查看 58.1K关注 0票数 23

如何用Python中的正则表达式替换文件中的字符串?

我想打开一个文件,在这个文件中我应该将字符串替换为其他字符串,我们需要使用正则表达式(搜索和替换)。打开文件并将其与搜索和替换方法一起使用的示例是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-28 21:09:46

代码语言:javascript
复制
# 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)
票数 41
EN

Stack Overflow用户

发布于 2016-02-28 21:01:06

这是一种通用格式。您可以根据您的需求使用re.sub或re.match。下面是打开并执行文件的一般模式:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35688126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档