2016-08-18 85 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