正则表达式在python中替换字符串的最佳方法是什么,但保留它的情况?

kei*_*rth 6 python regex

我想在python中替换字符串的实例但保留原始的情况.

例如,假设我用"香蕉"替换了字符串"鸡蛋":

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的方式.

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

tob*_*s_k 6

这里的关键见解是,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
Run Code Online (Sandbox Code Playgroud)

例:

>>> 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!
Run Code Online (Sandbox Code Playgroud)