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

解决:
  • 使用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)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-04
  • 2021-07-05
猜你喜欢
  • 2021-07-10
  • 2021-05-24
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2022-03-05
  • 2022-12-23
相关资源
相似解决方案