python - 替换文件中的所有正则表达式匹配项

标签 python regex

考虑一个基本的正则表达式,如 a(.+?)a。如何用第一组的内容替换文件中出现的所有该正则表达式?

最佳答案

使用可以使用 re 模块在 python 中使用正则表达式和 fileinput 模块简单地就地替换文件中的文本


示例:

import fileinput
import re

fn = "test.txt" # your filename

r = re.compile('a(.+?)a')
for line in fileinput.input(fn, inplace=True):
  match = r.match(line)
  print match.group() if match else line.replace('\n', '')

之前:

hello this
aShouldBeAMatch!!!!! and this should be gone
you know

之后:

hello this
aShouldBeAMa
you know


注意:这是有效的,因为参数 inplace=True 导致输入文件被移动到备份文件并且标准输出被定向到输入文件,如 documented under Optional in-place filtering

关于python - 替换文件中的所有正则表达式匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11898054/

相关文章:

java - Android 2.1 中的正则表达式负向预测

python - 在 keras 中构建简单线性模型时出现“数组不是 python 函数”错误

python - 重新引发异常,以便在同一 block 中处理它

python - 带有 : in name in lxml 的标签

java - 使用正则表达式替换字符的选定实例

php - 如何检查一个php字符串是否只包含英文字母和数字?

javascript - 正则表达式限制字母表

python - Django查询问题

python - 使用 Streamlit 部署 Scrapy 项目

php - 如何解析 PHP 中特定分隔部分的字符串?