I’m trying to convert a duration string like "2d1h30s"
to a total number of seconds. I’ve been using the re
package with the following regex:
duration = "2d1h30s"
matches = re.search(r"^(d+d)?(d+h)?(d+m)?(d+s)?$", duration, re.IGNORECASE)
# this gives me groups ['2d', '1h', None, '30s']
Note that the groups are optional, as in the example above the minutes are missing, which is fine. I’d like to remove the d|h|m|s
part of each match, i.e. get from ['2d', '1h', None, '30s')
to ['2', '1', None, '30']
using the regex. I’ve been researching this for a while but I’ve not found a way to combine the fact that the groups are optional with only wanting to capture part of the group.
I’m aware of the existence of the durations
package and I know I could simply remove the last character of each match using a list comprehension. Here I’m interested in learning how I can do it using only regex and optional capture groups.
Any suggestions? Thanks in advance 🙂