Python正则表达式问题:从天、小时、分钟中提取数字

3

我正在学习Python正则表达式,想知道如何从 x天y小时z分钟 中提取数字?

注意:没有月份或秒数,只允许一个或多个天、分钟和秒钟。

我的尝试

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

我在努力解决回顾环视的问题,如何解决?

1个回答

4
为什么要添加 ?<= ?看,我给你的正则表达式添加了分组并加上了缺失的空格分隔符,这样你就可以使用正则表达式进行匹配并选择分组。 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的海象运算符允许您避免执行a = True; if a: print(a)这样的操作。使用它,您可以执行if a:= True: print(a)。您可以在条件语句中声明变量!这里有一个很好的指南:https://realpython.com/lessons/assignment-expressions/ - Lucas Vazquez
非常感谢,有没有一种方法只提取数字?例如。match ['days'] = 5而不是'5天' - BhishanPoudel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接