2016-02-09 153 views
4

使用正則表達式替換單詞時,是否有一種優雅的方式表示我希望替換字符與被替換字的第一個字母的大寫/小寫匹配?如何用匹配的大小寫替換正則表達式?

foo -> bar 
Foo -> Bar 
foO -> bar 

的例子不區分大小寫的更換,但它不會正確地取代FooBar(它bar代替)。

re.sub(r'\bfoo\b', 'bar', 'this is Foo', flags=re.I) 
# 'this is bar' 

回答

4

開箱即用。您需要使用替換功能。

import re 

def cased_replacer(s): 
    def replacer(m): 
     if m.group(0)[0].isupper(): 
      return s.capitalize() 
     else: 
      return s 
    return replacer 

re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is foo', flags=re.I) 
# => 'this is bar' 
re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is Foo', flags=re.I) 
# => 'this is Bar' 
2

簡答:沒有。

龍答:

您可以通過使用finditer訪問所有的比賽,然後進行手工的情況下匹配做到這一點。

tests = (
     "11foo11", 
     "22Foo22", 
     "33foO33", 
     "44FOO44", 
) 

import re 
foobar = "(?i)(foo)" 

for teststr in tests: 
    replstr = "bar" 

    newchars = list(teststr) 

    for m in re.finditer(foobar, teststr): 
     mtext = m.group(1) 
     replchars = list(replstr) 

     for i, ch in enumerate(mtext): 
      if ch.isupper(): 
       replchars[i] = replchars[i].upper() 

     newchars[m.start():m.end()] = replchars 
     print("Old: ", teststr, " New: ", ''.join(newchars)) 
相關問題