【问题标题】:Regex pattern to split the string based on numeric characters基于数字字符拆分字符串的正则表达式模式
【发布时间】:2013-05-22 13:14:52
【问题描述】:

我想要一个正则表达式模式,根据字符串中存在的数字拆分字符串

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

是否可以通过正则表达式来执行此操作,否则最好的方法是什么?

【问题讨论】:

    标签: python regex string alphanumeric


    【解决方案1】:
    >>> 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']
    

    【讨论】:

    • 谢谢!你能解释一下这个模式吗?
    • @coding_pleasures 它查找数字序列\d 或非数字\D,然后捕获该序列,查看整个字符串。
    猜你喜欢
    • 2021-10-25
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多