简体   繁体   English

提取两个特殊字符之间的字符串并将其替换为 python 中的新字符串

[英]Extracting String between two special characters and replacing it with new string in python

I am trying to extract a string between two characters and replace it with a new string in every occurance of old string in a file.我试图在两个字符之间提取一个字符串,并在文件中每次出现旧字符串时用一个新字符串替换它。

Example:例子:

Str1= "portid.router.address_location" Str1="portid.router.address_location"

str2= "$addressmap= portid.ipaddress" str2= "$addressmap= portid.ipaddress"

Str1 and Str2 are part of single file. Str1 和 Str2 是单个文件的一部分。 Also, str1 and str2 has numerous occurrences in my text file and I need to replace each occurrence of "portid" string with a string called "devicenumber'.此外,str1 和 str2 在我的文本文件中出现了很多次,我需要将每次出现的“portid”字符串替换为一个名为“devicenumber”的字符串。

Correction to my question: portid variable is not stable one.更正我的问题:portid 变量不稳定。 port id variable will be keep changing for each file.每个文件的端口 id 变量将不断变化。 Example: "portid_id6_add7" in one file and "portid_id100_add7"示例:一个文件中的“portid_id6_add7”和“portid_id100_add7”

If you want to use the regex module in python specifically then try something like to replace the occurence of a particular string with something else:如果您想专门使用 python 中的regex模块,请尝试使用其他内容替换特定字符串的出现:

import re

lst = ['portid.router.address_location', '$addressmap= portid.ipaddress']
regex = re.compile('portid')

for string in lst:
   regex.sub('devicenumber', string)

Put this into your python shell and you will see every modified string.将其放入您的 python shell 中,您将看到每个修改后的字符串。

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

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