【问题标题】:python regex problem extract numbers from days hours minutespython 正则表达式问题从天小时分钟中提取数字
【发布时间】:2020-04-21 23:34:11
【问题描述】:

我正在学习 python 正则表达式,想知道如何从中提取数字 x days y hours z minutes?

注意:没有月或秒,只允许天、分和秒中的一种或多种。

我的尝试

import re

s1 = '5 days 19 hours 30 minutes'
s2 = '5 days'
s3 = '19 hours'
s4 = '5 days 19 hours'

pat = r'((\d+)(?<=\sdays))?((\d+)(?<=\shours))?((\d+)(?<=\sminutes))?'


d,h,m = re.findall(pat,s)

Note: 2 days 3 hours ==> d=2 h=3
      2 hours 3 minutes ==> h=2 m=3

我正在努力解决后视问题。如何解决问题?

【问题讨论】:

    标签: python python-re


    【解决方案1】:

    为什么要添加 ?&lt;= ? 看,我将组添加到您的正则表达式并添加缺少的空格分隔符

    然后您可以匹配您的正则表达式并选择组。

    Python 3.7

    import re
    
    s4 = '5 days 19 hours'
    pat = r'(?P<days>(\d+)(\sdays))? ?(?P<hours>(\d+)(\shours))? ?(?P<minutes>(\d+)(\sminutes))?'
    
    match = re.match(pat, s4)
    if match:
        print(match.groupdict())  # print all groups
    
    # Output: {'days': '5 days', 'hours': '19 hours', 'minutes': None}
    

    如果您只想匹配值的数量,而不是名称和数字,则需要使用下一个模式:

    r'((?P<days>\d+) days)? ?((?P<hours>\d+) hours)? ?((?P<minutes>\d+) minutes)?'
    
    """
    Here I deconstruct the pattern,
    then you can look at it and the next time you can make your own without help.
    
    ((?P<days>\d+) days)?          Match numbers + space + "days"
     ?                             Match space
    ((?P<hours>\d+) hours)?        Match numbers + space + "hours"
     ?                             Match space
    ((?P<minutes>\d+) minutes)?    Match numbers + space + "minutes"
    
    If you want the group "days" return you the number and the word "days" yo need to use it as:
    (?P<days>\d+ days)
    """
    
    

    https://regex101.com/ 是尝试您的模式的好地方。它有一个很好的 IDE,可以帮助您了解每个元素的作用。

    【讨论】:

    • python 3.8 的 walrus 运算符可以让你避免做a = True; if a: print(a)。有了它你可以做if a:= True: print(a)。您可以在条件中声明一个变量!有一个很好的指南:realpython.com/lessons/assignment-expressions
    • 非常感谢,有没有办法只提取数字?例如。 match['days'] = 5 instead of '5 days'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多