替换文件中两个字符之间的字符串

Replacing string between two characters in the file

我的属性文件中有如下字符串:

line = "variables=ORACLE_BASE_HOME=/u02/test/oracle/landscape/1/db_50,DB_UNIQUE_NAME=cdms,ORACLE_BASE=//u02/test,PDB_NAME=,DB_NAME=cdms,ORACLE_HOME=/u02/test/product/19/db_21,SID=ss"

我想用不同的值替换以下字符串:

DB_NAME=cdms -> DB_NAME=abc

我有下面的代码,但是,它似乎没有按预期运行:

f = fileinput.FileInput(rsp_file_path)
for line in f:
    re.sub(",DB_NAME=(.*?),", "abc", line, flags=re.DOTALL)
f.close()

你可以使用 string.replace()

s.replace('DB_NAME', 'cdms', 1).replace('DB_NAME', 'abc', 1)

应该是:

re.sub("(,DB_NAME=)(.*?),", "\g<1>abc,", line, flags=re.DOTALL)

或使用原始字符串:

re.sub(r"(,DB_NAME=)(.*?),", r"abc,", line, flags=re.DOTALL)

那是因为 re.sub()documentation 声明:

In string-type repl arguments, in addition to the character escapes and backreferences described above, \g will use the substring matched by the group named name, as defined by the (?P...) syntax. \g uses the corresponding group number; \g<2> is therefore equivalent to , but isn’t ambiguous in a replacement such as \g<2>0. would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.

在您的情况下,(,DB_NAME=) 是您用 \g<1> 引用的第一个捕获组。