简体   繁体   中英

Replacing string between two characters in the file

I have a string in my proprieties file as below:

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:

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 \\2, but isn't ambiguous in a replacement such as \\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'. The backreference \\g<0> substitutes in the entire substring matched by the RE.

In your case (,DB_NAME=) is the first captured group which you refer to with \\g<1> .

你可以使用 string.replace()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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