0

I am trying to find the time (HH:MM) in string (12 hours ) but the code doesn't work. Hope you can help.

python 
import re
pattern = r'^(0?[1-9]|1[0-2]):[0-5][0-9]$'
test_string = 'my activestate platform account is 12:30 now active' 
result = re.findall(pattern, test_string)
print(result)
Ana
  • 19
  • 3

1 Answers1

2

You regex is anchored at the start (^) and end ($) of your string. Just remove these, since the time is not necessarily the beginning and end of your input!

Also, If you want to capture the whole match, you may want to tweak the regex as this:

r'((?:0?[1-9]|1[0-2]):[0-5][0-9])'.

(the (?: ) is a non-capturing group, so that the hours alone are not dumped in the results of findall)

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • I don't understand what the `(?:` are doing at the front of that expression. – Mark Ransom May 02 '21 at 20:58
  • it means it's a non-capturing group. That's a group, because, it's inside parenthesis `()`, to be able to use the 'or' syntax with`|`, but it's not "capturing", i.e. it's not in the results by itself. If you remove the `?:`, you'll get two groups: `['12:30', '12']` (the outer enclosing group, then the smaller inner group). See also: https://stackoverflow.com/questions/18425386/re-findall-not-returning-full-match for more info. – Pac0 May 03 '21 at 01:19
  • 1
    I guess I've never done such a deep dive into the regex syntax, thanks for the detailed explanation and link. – Mark Ransom May 03 '21 at 03:14