2016-08-18 79 views
1

例如,我有一个字符串:如何用匹配的转换替换重新匹配?

The struct-of-application and struct-of-world 

随着re.sub,它将替换预定义的字符串匹配。如何将匹配替换为匹配内容的转换?为了获得,例如:

The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct) 

如果我写了一个简单的正则表达式((\w+-)+\w+),并尝试使用re.sub,看来我不能用我作为替代的一部分匹配,更不用说编辑匹配的内容:

In [10]: p.sub('struct','The struct-of-application and struct-of-world') 
Out[10]: 'The struct and struct' 
+0

@ KevinJ.Chase我将添加re.sub的结果很快 – KIDJourney

+0

使用多行代码? – wwii

+0

@wwii如何?搜索并替换? – KIDJourney

回答

2

使用function for the replacement

s = 'The struct-of-application and struct-of-world' 
p = re.compile('((\w+-)+\w+)') 
def replace(match): 
    return 'http://{}'.format(match.group()) 

>>> p.sub(replace, s) 

'The http://struct-of-application and http://struct-of-world' 
>>> 
+0

这就是我需要的。感谢分享:) – KIDJourney

+0

有了这个功能,你可以构建替换你心中的内容。 – wwii

1

试试这个:

>>> p = re.compile(r"((\w+-)+\w+)") 
>>> p.sub('[\\1](http://\\1)','The struct-of-application and struct-of-world') 
'The [struct-of-application](http://struct-of-application) and [struct-of-world](http://struct-of-world)' 
+0

我不知道我是否可以编辑它匹配的内容,并用它来取代? – KIDJourney