why you add ?<= ? Look, I add groups to your regex and add missing space separations
Then you can match for your regex and select groups.
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}
If you only want to match the number of the values, instead the name and the number, you need to use the next pattern:
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/ is a good place to try your patterns. It has a good IDE that helps you to understand what each element do.