3

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.

user9127040
  • 71
  • 1
  • 7

3 Answers3

1

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.

Jan
  • 42,290
  • 8
  • 54
  • 79
0

I would use a different regex: (0*[1-9]|1[0-9]|2[0-3]):[0-5][0-9]|24:00, which is an adapted version of Regular expression for matching HH:MM time format

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

In your given example the time is always placed inside two `. If this is always the case for the given time you could simplify the regex to

import re
response = re.sub(r'`.+`',
                 '7:15', 
                 'I will be there at `24:00` later today')
print(response)
wake-0
  • 3,918
  • 5
  • 28
  • 45
0

You can try simple and minimal approach with this pattern :

import re
pattern=r'\d{1,2}:\d{2}'
text='I will be there at 4:15 later today'

match=re.findall(pattern,text)
print(match)

output:

['4:15']