【问题标题】:Replace strings in a file using regular expressions使用正则表达式替换文件中的字符串
【发布时间】:2016-02-28 20:52:36
【问题描述】:

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

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

【问题讨论】:

  • re.sub 是你想要的功能
  • @Arman 我想你的意思是re.sub

标签: python regex


【解决方案1】:
# 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)

【讨论】:

  • “mm”是指 11,而不是 NOV(有 3 个字符),对吗?但是随后您使用 \w 将其匹配为字符词而不是像其他数字一样的 \d 数字,因此 'mm' 也需要匹配为 \d。
  • 你是对的@R.Navega ; \d{2}(适用于 11)或 \w{3}(适用于 nov)
  • 感谢 @R.Navega 和 @gildux 的 cmets。我已更新正则表达式以包含日期格式,例如 11/30/2016
  • @lucidbrot:对于第一个,有没有r,在这个具体场景下,没有区别。有一个线程,你可以看看:stackoverflow.com/questions/8157267/…
  • @Timo:是的,当然。
【解决方案2】:

这是一个通用格式。您可以根据需要使用 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)

【讨论】:

  • 不适用于多行正则表达式。
  • 谢谢,我只是 python 的初学者,我们的项目是在 Python 中创建脚本,其中包含字符串 xkcd (norvig.com/ipython/xkcd1313.ipynb) 将替换 bu.*ls 为字符串 [gikuj].. n|a.[alt]|[pivo].l|i..o|[jocy]e|sh|di|oo 以及 where are characters = a [ 它将用我们的名字替换它......所以这就是我问这个问题的原因,因为我完全迷路了..
  • 我认为您应该清楚地制定您的要求并开始尝试这里的一些示例以从pymotw.com/2/re开始
猜你喜欢
  • 2021-10-10
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2015-11-30
相关资源
最近更新 更多