Be Chiller Too
Be Chiller Too

Reputation: 2910

Replacing regex with optional pattern

I want to convert time separator from the French way to a more standard way:

Using regexp I can transform 17h30 to 17:30 but I did not find an elegant way of transforming 9h into 9:00

Here's what I did so far:

import re
texts = ["17h30", "9h"]
hour_regex = r"(\d?\d)h(\d\d)?"
[re.sub(hour_regex, r"\1:\2", txt) for txt in texts]
>>> ['17:30', '9:']

What I want to do is "if \2 did not match anything, write 00".

PS: Of course I could use a more detailed regex like "([12]?\d)h[0123456]\d" to be more precise when matching hours, but this is not the point here.

Upvotes: 1

Views: 57

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Effectively with re.compile function and or condition:

import re

texts = ["17h30", "9h"]
hour_regex = re.compile(r"(\d{1,2})h(\d\d)?")
res = [hour_regex.sub(lambda m: f'{m.group(1)}:{m.group(2) or "00"}', txt) 
       for txt in texts]
print(res)   # ['17:30', '9:00']

Upvotes: 4

Austin
Austin

Reputation: 26039

You can do a slight (crooked) way:

import re

texts = ["17h30", "9h"]
hour_regex = r"(\d?\d)h(\d\d)?"

print([re.sub(r':$', ':00', re.sub(hour_regex, r"\1:\2", txt)) for txt in texts])
# ['17:30', '9:00']

Upvotes: 1

Related Questions