使用正则表达式替换文件中的字符串 [英] Replace strings in a file using regular expressions

查看:32
本文介绍了使用正则表达式替换文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I replace strings in a file with using regular expressions in Python?

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

I want to open a file in which I should replace strings for other strings and we need to use regular expressions (search and replace). What would be some example of opening a file and using it with a search and replace method?

推荐答案

# 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)

这篇关于使用正则表达式替换文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆