2016-11-18 28 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'