替换字符串中与 python 2.7 中的模式匹配的特定部分并保存在同一文件中

Replace a certain part of the string which matches a pattern in python 2.7 and save in the same file

我正在努力实现这样的目标

我的输入文件有这种条目

art.range.field = 100
art.net.cap = 200
art.net.ht = 1000
art.net.dep = 8000

我正在尝试匹配 art.range.field 这样的模式,那里的值应该更改为 500。所以代码的输出应该是这样的

art.range.field = 500
art.net.cap = 200
art.net.ht = 1000
art.net.dep = 8000

下面是我解决这个问题的尝试

file_path = /tmp/dimension
with open(file_path,"r") as file
  file_content = file.read()
  new_content = re.sub(r"^.*"+parameter+".*$",parameter+" = %s" % value, file_content)
  file.seek(0)
  file.write(new_content)
  file.truncate()

这里我取了parameter = art.range.fieldvalue = 500

但我的文件仍然保持不变,因为 new_content 变量没有将其值更改为所需的输出。

所以我想知道我哪里出错了,可能的解决方案是什么。

您没有更改任何内容,因为您未处于多行模式。如果您将 (?m) 添加到您的正则表达式(在 ^ 之前),它应该可以工作。另请参阅 this resource 以深入了解正则表达式修饰符的论点。

此外:

  • 你不需要 $,因为你不是在单行模式下,所以使用 .* 你将只匹配所有字符直到行尾。
  • 为了避免误报,我还要确保 parameter 后跟一个等号。
  • 如果您想将参数用作正则表达式的一部分,最好对参数进行转义(使用 re.escape 方法)。

所以你应该使用这行代码:

new_content = re.sub(r"(?m)^\s*" + re.escape(parameter)  +"\s*=.*", parameter + " = " + value, file_content)

你可以得到你想要的

import re
parameter = 'art.range.field'
value = 500
with open(file_path,"r+") as file:
    new_content = re.sub(r"^("+re.escape(parameter)+r"\s*=\s*).*", r"\g<1>%d" % value, file.read(), flags=re.M)
    file.seek(0)
    file.write(new_content)
    file.truncate()

参见regex demo

:

  • 您需要使用 r+ 才能真正 read/write 到文件
  • re.M 匹配带有 ^
  • 的任何行的开头
  • re.escape 转义 parameter 变量中的特殊字符

正则表达式详细信息:

  • ^ - 行首
  • (art\.range\.field\s*=\s*) - 第 1 组(\g<1> 在替换模式中,需要明确的反向引用,因为 value 以数字开头):
    • art\.range\.field - art.range.field 字符串
    • \s*=\s* - 包含 0+ 个空格的 =
  • .* - 除换行字符外的任何 0 个或更多字符尽可能多