在python中提取两个特殊字符之间的字符串并用新字符串替换



我试图提取两个字符之间的字符串,并在文件中每次出现旧字符串时用新字符串替换它。

示例:

Str1=";portid.router.address_location";

str2="$addressmap=portid.ipaddress";

Str1和Str2是单个文件的一部分。此外,str1和str2在我的文本文件中有很多次出现,我需要替换每次出现的";portid";字符串与一个名为";设备编号'。

更正我的问题:portid变量不是稳定变量。端口id变量将为每个文件不断更改。示例:";portid_6_add7";在一个文件中;portid_ id100_add7";

如果你想在python中专门使用regex模块,那么试着用其他东西替换特定字符串的出现:

import re
lst = ['portid.router.address_location', '$addressmap= portid.ipaddress']
regex = re.compile('portid')
for string in lst:
regex.sub('devicenumber', string)

把这个放到你的python shell中,你会看到每一个修改过的字符串。

最新更新