2013-05-22 34 views
1

我想有一個正則表達式的字符串分割其將基於存在於他們正則表達式模式基於數字字符

50cushions => [50,cushions] 
30peoplerescued20children => [30,peoplerescued,20,children] 
moon25flightin2days => [moon,25,flightin,2,days] 

數字字符串是否有可能做到這一點正則表達式,或其他什麼是最好的辦法呢?

回答

4
>>> re.findall(r'\d+|\D+', '50cushions') 
['50', 'cushions'] 
>>> re.findall(r'\d+|\D+', '30peoplerescued20children') 
['30', 'peoplerescued', '20', 'children'] 
>>> re.findall(r'\d+|\D+', 'moon25flightin2days') 
['moon', '25', 'flightin', '2', 'days'] 

其中\d+一個或多個數字和\D+匹配一個或多個非數字相匹配。 \d+|\D+會找到(|)一組數字或非數字,並將結果追加到匹配列表中。

或用itertools

>>> from itertools import groupby 
>>> [''.join(g) for k, g in groupby('moon25flightin2days', key=str.isdigit)] 
['moon', '25', 'flightin', '2', 'days'] 
+1

謝謝!你能否介紹一下這個模式。 –

+1

@coding_pleasures它會查找數字序列'\ d'或非數字'\ D',然後捕獲該序列,查看整個字符串。 – HennyH

+0

謝謝@HennyH。正則表達式模式使它看起來很簡單.. –