进行区分大小写的替换但匹配要替换单词的大小写的最佳方法? [英] Best way to do a case insensitive replace but match the case of the word to be replaced?

查看:236
本文介绍了进行区分大小写的替换但匹配要替换单词的大小写的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我想出了下面的方法,但是我的问题是,那里是否有一个较短的方法具有相同的结果?

So far I've come up with the method below but my question is is there a shorter method out there that has the same result?

input_str       = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
replace_str     = "stuff"
replacer_str    = "banana"


print input_str
# prints: myStrIngFullOfStUfFiWannAReplaCE_StUfFs

if replace_str.lower() in input_str.lower():            # Check if even in the string
    begin_index = input_str.lower().find( replace_str )
    end_index   = begin_index + len( replace_str )

    replace_section = input_str[ begin_index : end_index ]

    case_list = []
    for char in replace_section:                        # Get cases of characters in the section to be replaced
        case_list.append( char.istitle() )

    while len( replacer_str ) > len(case_list):
        case_list += case_list

    sameCase_replacer_str   = ""                        # Set match the replacer string's case to the replace
    replacer_str            = replacer_str.lower()
    for index in range( len(replacer_str) ):
        char = replacer_str[ index ]
        case = case_list[ index ]
        if case == True:
            char = char.title()

        sameCase_replacer_str += char

    input_str = input_str.replace( replace_section , sameCase_replacer_str )

print input_str
# prints: myStrIngFullOfBaNaNAiWannAReplaCE_BaNaNAs

推荐答案

我会使用类似这样的东西:

I'd use something like this:

import re

def replacement_func(match, repl_pattern):
    match_str = match.group(0)
    repl = ''.join([r_char if m_char.islower() else r_char.upper()
                   for r_char, m_char in zip(repl_pattern, match_str)])
    repl += repl_pattern[len(match_str):]
    return repl

input_str = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
print re.sub('stuff',
             lambda m: replacement_func(m, 'banana'),
             input_str, flags=re.I)

示例输出:

myStrIngFullOfBaNaNaiWannAReplaCE_BaNaNas

myStrIngFullOfBaNaNaiWannAReplaCE_BaNaNas

注意:

  • 这处理了不同的匹配具有不同的大小写组合的情况.
  • 假定替换模式为小写字母(无论如何都非常容易更改).
  • 如果替换模式比匹配项长,则使用与模式相同的情况.

这篇关于进行区分大小写的替换但匹配要替换单词的大小写的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆