我的字符串是
I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny
所以我不想替换“Destiny”
TAG:{Destiny2,the last Destiny game}
但我想用
替换最后一个词“命运”TAG:{Destiny:Destiny}
我总是想在替换时忽略 TAG 中的字符串。
预期输出:
I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny:Destiny}
请帮忙。
最佳答案
您需要首先解析字符串,找出哪些 Destiny
子字符串位于标记内,哪些不在标记内。我在下面使用 re.split 完成了此操作.
我使用 re.split 返回围绕正则表达式模式 TAG:?{.*?}
的子字符串列表,并且因为我将模式括在括号中,所以标签包含在列表中以及。在使用 re.split 时,非标签将始终具有偶数索引,而标签将始终具有奇数索引。因此,我检查索引是否为偶数,如果是偶数,则将 Destiny
替换为 TAG:{Destiny,Destiny}
。
import re
s = 'TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny'
result = []
for i, substring in enumerate(re.split('(TAG:?{.*?})', s)):
if i % 2 == 0:
substring = substring.replace('Destiny', 'TAG:{Destiny,Destiny}')
result.append(substring)
result = ''.join(result)
print(result) # TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny,Destiny}
只要您没有将标签嵌套在其他标签内,此方法就可以工作。
关于python - 忽略python中字符串的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50145412/