【问题标题】:What's the best way to regex replace a string in python but keep its case? [duplicate]正则表达式替换python中的字符串但保持大小写的最佳方法是什么? [复制]
【发布时间】:2014-07-22 17:29:55
【问题描述】:

我希望在 python 中替换字符串的实例,但保留原来的大小写。

例如,假设我将字符串 'eggs' 替换为 'bananas':

This recipe requires eggs. --> This recipe requires bananas.

Eggs are good for breakfast. --> Bananas are good for breakfast.

I'M YELLING ABOUT EGGS! --> I'M YELLING ABOUT BANANAS!

现在,我执行了 re.compile 和 .sub,但如果不每次都明确声明这三个变体,我就无法找到一种聪明的方法。我正在替换大约 100 多个单词,所以我想必须有一种更智能、更 Pythonic 的方式。

编辑:这不是先前提出的问题的重复。 --> 一些不同之处:我用一个完全不同的词替换了这个词,而不是将它包装在标签中。另外,我需要保留这个案例,即使它全部大写等。请不要在没有完全阅读问题的情况下标记为重复。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    这里的关键见解是,您可以将一个函数传递给re.sub,以便在确定给定匹配项的正确替换之前进行各种检查。另外,使用re.I 标志来获取所有案例。

    import re
    def replace_keep_case(word, replacement, text):
        def func(match):
            g = match.group()
            if g.islower(): return replacement.lower()
            if g.istitle(): return replacement.title()
            if g.isupper(): return replacement.upper()
            return replacement      
        return re.sub(word, func, text, flags=re.I)
        # return re.compile(word, re.I).sub(func, text) # prior to Python 2.7
    

    例子:

    >>> text = "Eggs with eggs, bacon and spam are good for breakfast... EGGS!"
    >>> replace_keep_case("eggs", "spam", text)
    Spam with spam, bacon and spam are good for breakfast... SPAM!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多