2016-11-18 27 views
1

我使用Python的味道,如果正則表達式,我需要一個切片的字符串,而替換文本。我用來匹配我需要的字符串的正則表達式是abc .+ cba。如果匹配abc Hello, World cba,那應該更改爲efg Hello, World正則表達式字符切片

回答

3

使用捕獲組:

>>> s = "here is some stuff abc Hello, World cba here is some more stuff" 
>>> import re 
>>> re.sub(r'abc (.+) cba', r'efg \1',s) 
'here is some stuff efg Hello, World here is some more stuff' 
>>> 

注:替換字符串接受一個反向引用。

2

可以使用如下函數應用re.sub:

re.sub(pattern, repl, string, count=0, flags=0) 

在repl時,支持使用\ 1,\ 2 ...到反向引用由組1,2中的圖案匹配的字符串... ,使用()。對於這一次,它的(+)

>>> import re 
>>> re.sub(r"abc (.+) cba",r"efg \1", "abc Hello, World cba") 
'efg Hello, World'