2012-06-26 47 views
1

我能夠使用的情況下,下面的解決方案不敏感的方法替換字符串中的內容一個字不區分大小寫字符串替換在python

http://code.activestate.com/recipes/552726/ 
import re 

class str_cir(str): 
     ''' A string with a built-in case-insensitive replacement method ''' 

     def ireplace(self,old,new,count=0): 
     ''' Behaves like S.replace(), but does so in a case-insensitive 
     fashion. ''' 
      pattern = re.compile(re.escape(old),re.I) 
      return re.sub(pattern,new,self,count) 

我的問題是我需要更換正是我提供類似的詞

para = "Train toy tram dog cat cow plane TOY Joy JoyTOY" 

我需要 「火腿」 一詞取代 「玩具」,我也得到

'Train HAM tram dog cat cow plane HAM Joy JoyHAM' 

瓦在我需要的是

'Train HAM tram dog cat cow plane HAM Joy JoyTOY' 
+0

只是要注意 - 縮進不正確 - 我認爲實際代碼是'para = str_cri(「...」) –

+0

錯字錯誤已更正 – Rakesh

+0

[不區分大小寫替換](https: //backoverflow.com/questions/919056/case-insensitive-replace) –

回答

4

添加\b到關鍵字的開始和結束:

pattern = re.compile("\\b" + re.escape(old) + "\\b",re.I) 

\b意味着字邊界,並且它在一個單詞的開始和結束匹配空字符串(由字母數字或下劃線字符的序列來定義)。 (Reference

正如@Tim Pietzcker指出的那樣,如果關鍵字中包含非單詞(不是字母數字和下劃線)字符,它將無法像您所想的那樣工作。

+1

這。 (讓我們只希望他的搜索「單詞」永遠不會以非字母數字字符開始或結束) –

+0

嗨,這個方法適用於我,因爲我搜索的術語總是字母數字字符。謝謝 – Rakesh

2

\b在正則表達式的開始和結束。

2

在正則表達式中使用單詞邊界(\b)包裝您正在使用的單詞。

+0

把'\ b'放在兩端應該和把'^'放在開頭和'$'放在一起? – theharshest

+0

@theharshest Nope,'\ b'是字符串的邊界,而'^'和'$'位置位於字符串的開始和結尾。 – alex

+0

但是如果我在開始和結束時放入'^'和'$',那麼它也會匹配確切的重新封閉,解決與'\ b'相同的目的。對? – theharshest

相關問題