簡體   English   中英

正則表達式模式可根據數字字符拆分字符串

[英]Regex pattern to split the string based on numeric characters

我想有一個正則表達式模式,可以根據其中存在的數字來拆分字符串

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

是否有可能這樣做正則表達式,否則最好的方法是什么?

>>> 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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM