代码之家  ›  专栏  ›  技术社区  ›  Sridhar Ratnakumar

如何不敏感地替换非静态子串大小写

  •  1
  • Sridhar Ratnakumar  · 技术社区  · 16 年前

    这个问题类似于 this

    我想写下 ireplace ,其行为如下:

    >>> ireplace(r'c:\Python26\lib\site.py', r'C:\python26', r'image\python26')
    r'image\python26\lib\site.py'
    >>>
    
    2 回复  |  直到 9 年前
        1
  •  1
  •   John La Rooy    16 年前

    在这种情况下,我认为这是最简单的方法

    r'c:\Python26\lib\site.py'.lower().replace('python26', r'image\python26')
    

    >>> def ireplace(s, a, b):
    ...     return re.sub("(?i)"+re.escape(a),b,s)
    ...
    >>> print ireplace(r'c:\Python26\lib\site.py', 'C:\python26', r'image\python26')
    image\python26\lib\site.py
    
        2
  •  0
  •   Sridhar Ratnakumar    16 年前
    def ireplace(s, a, b):
        """Replace `a` with `b` in s without caring about case"""
        re_a = re.compile(re.escape(a), re.IGNORECASE)
        return re_a.sub(lambda m: b, s)
    

    注:以下为 lambda m: b re.escape(b) 如果它有连字符,似乎会弄坏字符串。