字符串忽略大小写的搜索和替换

需求:字符串忽略大小写搜索和替换

解决:
  • 使用re.IGNORECASE
import re

text = 'UPPER PYTHON, lower python, Mixed Python'


f = re.findall("python", text, flags=re.IGNORECASE)
print(f)
s, n = re.subn("python","snake",text, flags=re.IGNORECASE)
print(s)
print(n) # 返回匹配的次数
缺陷
替换之后的字符串与被替换的大小写不能保持一致
解决:
def matchcase(word):
    def replace(m): # 匹配的结果 如:PYTHON
        text = m.group()
        if text.isupper():
            return word.upper()
        elif text.islower():
            return word.lower()
        elif text[0].isupper():
            return word.capitalize()
        else:
            return word

    return replace


if __name__ == '__main__':
    s = re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
    print(s)

posted on 2019-11-05 21:08  action555  阅读(370)  评论(0编辑  收藏  举报