2013-05-22 32 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。正则表达式模式使它看起来很简单.. –