替换感兴趣字符串的完全不敏感匹配,同时忽略具有部分i的其他字符串

2024-06-17 17:56:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难替换字符串的完全不敏感匹配,而不会影响较大的字符串(其中包含感兴趣的字符串的一部分)

我的意思是:如果我有一个字符串“INFO”,我想用“INFORMATION”替换它,如果我找到一个字符串“INFOR”,我不想做任何事情,因为它与“INFO”不完全匹配

我是用python做的:

string = re.compile(re.escape("info"), re.IGNORECASE)
string = string.sub("information", "This might be related to info disclosure. Because Infor disclosure....")
print(string)

我得到的结果是:

This might be related to information disclosure. Because informationr disclosure....

这不是我想要的,因为infor正在被information所取代

有办法解决吗


Tags: to字符串reinfostringinformationbethis
1条回答
网友
1楼 · 发布于 2024-06-17 17:56:09

正则表达式可以解决您的问题。 您可以使用re-library,只需在“info”前后留出空间:

import re
string = re.compile(re.escape(" info "), re.IGNORECASE)
string = string.sub(" information ", "This might be related to iNfo disclosure. Because Infor disclosure....")
print(string)

相关问题 更多 >