简体   繁体   English

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

[英]Replacing string between two characters in the file

I have a string in my proprieties file as below:我的proprieties文件中有一个字符串,如下所示:

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"

I would like to replace the following string with a different value:我想用不同的值替换以下字符串:

DB_NAME=cdms -> DB_NAME=abc

I have the code below, however, it seems not doing as expected:我有下面的代码,但是,它似乎没有按预期工作:

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

It should be:它应该是:

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

or using raw string:或使用原始字符串:

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

That's because the documentation for re.sub() states:那是因为re.sub()文档指出:

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.在字符串类型的 repl 参数中,除了上面描述的字符转义和反向引用之外,\\g 将使用由 (?P...) 语法定义的名为 name 的组匹配的子字符串。 \\g uses the corresponding group number; \\g 使用对应的组号; \\g<2> is therefore equivalent to \\2, but isn't ambiguous in a replacement such as \\g<2>0. \\g<2> 因此等价于 \\2,但在诸如 \\g<2>0 之类的替换中并不含糊。 \\20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. \\20 将被解释为对组 20 的引用,而不是对组 2 后跟文字字符“0”的引用。 The backreference \\g<0> substitutes in the entire substring matched by the RE.反向引用 \\g<0> 替换 RE 匹配的整个子字符串。

In your case (,DB_NAME=) is the first captured group which you refer to with \\g<1> .在您的情况下(,DB_NAME=)是您使用\\g<1>引用的第一个捕获组。

你可以使用 string.replace()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM