Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my time replacing regex working?

Tags:

python

regex

The kind of sentences expected :

I will be there at 4:15 later today

I will be there at 14:06 later today.

Few things to notice there:

1- The hour format is 24h

2- The hour can be one letter or 2 while the minutes is always 2.

3- The time is always mid sentence .

what i have tried :

import re

response = re.sub(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$',
                                     '7:15', 'I will be there at `4:15` later today')

I also tried this regex ^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$ and it also didn't work.

like image 682
user9127040 Avatar asked Nov 30 '25 07:11

user9127040


1 Answers

A couple of issues here but this works:

import re

response = re.sub(r'(?:[01]?\d|2[0-3]):(?:[0-5]\d)|24:00', '7:15', 'I will be there at `4:15` later today')
print(response)

This yields

I will be there at `7:15` later today

You need to get rid of the anchors and make [01] optional with a ?. Lastly, change the parentheses to non-capturing and remove non-necessary parentheses.

like image 198
Jan Avatar answered Dec 01 '25 20:12

Jan