2016-08-22 38 views
1

我有一個正則表達式,通過該我想與那些值減去10 重新是替換值:的Python重新更換組值

re.compile(r'<stuff[^\>]*translate\((?P<x>\d*),(?P<y>\d*)\)"/>') 

我想要替換x和y的基團。要做到這一點,我想使用re.sub並傳遞一個函數。然而,在函數中,我怎樣才能最輕鬆地構建一個與輸入相同的字符串,只需要將x和y值自己替換爲10呢?

+0

看看[這裏](http://stackoverflow.com/questions/2763750/how-to-replace-only-part-of -py-re-sub-python-re-sub)回答一個更清晰的方法 – FujiApple

回答

0

re.sub docs顯示了使用替代功能的一個很好的例子。在你的情況,這會工作:

import re 

def less10(string): 
    return int(string) - 10 

def replacer(match): 
    return '%s%d,%d%s' % (match.group('prefix'), 
          less10(match.group('x')), 
          less10(match.group('y')), 
          match.group('suffix')) 

print re.sub(r'(?P<prefix><stuff[^>]*translate\()(?P<x>\d*),(?P<y>\d*)(?P<suffix>\)/>)', 
      replacer, 
      '<stuff translate(100,200)/>') 

http://ideone.com/tQS4wK

+0

但是,這並不會將新值替換爲字符串。我想用新的x和y值替換同一個輸入字符串,但其他部分都一樣。 – Sandeep

+0

好的。這在你的問題中並不清楚。 – tony19

+0

我更新了問題以使其更清楚。 – Sandeep