如何在 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)
关于python - 使用正则表达式替换文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688126/