在Python中如何正则替换字符串并保留大小写?

10 投票
1 回答
3056 浏览
提问于 2025-04-18 14:18

我想在Python中替换字符串,但要保持它们原来的大小写。

比如说,我想把字符串'eggs'替换成'bananas':

这个食谱需要鸡蛋。 --> 这个食谱需要香蕉。

鸡蛋对早餐很好。 --> 香蕉对早餐很好。

我在大声喊鸡蛋! --> 我在大声喊香蕉!

现在,我用re.compile和.sub来做,但我不知道怎么做得更聪明一点,而不需要每次都明确写出三种变体。我需要替换大约100多个单词,所以我想应该有更聪明、更符合Python风格的方法。

编辑:这不是之前问过的问题的重复。 --> 有一些不同之处:我替换的是一个完全不同的单词,而不是把它包裹在标签里。此外,我需要保持大小写,即使是全大写也要保持。请不要在没有完全阅读问题的情况下标记为重复。

1 个回答

16

这里的关键点是,你可以把一个函数传递给 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!"

撰写回答