PUB-DB来正则化替换

json文件中,想要用(PUB-DB)来正则化替换.*(PUB-DB).*,例如NFV-R-HBLF-1313E-HW-13-VM-PUB-DB-01和
KVM-HW-VM-PUB-DB-02和
KVM-HW-VM-PUB-DB-01和
-VM-PUB-DB-02和
KM-PUB-DB-02

.*是想前后的内容你都可以自己替换吗,这里我使用\1 和\2 分别表示匹配到的内容前面和后面部分

img

import re

pattern = r"(.*?)\\(PUB-DB\\)(.*?)"
replacement = r"\\1(PUB-DB-normalized)\\2"

string_first = "NFV-R-HBLF-1313E-HW-13-VM-PUB-DB-01"
string_second= "KVM-HW-VM-PUB-DB-02"

print(re.sub(pattern, replacement, string_first))
print(re.sub(pattern, replacement, string_second))