0

I have the email content. From this content I then want to extract any times that exist. The times are in 24 hour format, contain a colon separator (eg 13:00) and can appear anywhere in the text.

As an example:

"Some text some text some text 12:00 Some text some text some text"

When I use this line to extract the time, the result is blank:

tp_time = re.findall(r'(^[0-2][0-3]:[0-5][0-9]$)', tp_msg)
print(tp_time)

Can anyone see what I am doing wrong?

2
  • 1
    The times "are in 24 hour format" but [0-2][0-3]:[0-5][0-9] will not match e.g. 17:00. What's going on? Commented Oct 7, 2021 at 9:45
  • 1
    Should have used (2[0-3]|[0-1][0-9]):[0-5][0-9] instead. Commented Oct 7, 2021 at 9:53

2 Answers 2

4

Can anyone see what I am doing wrong?

You are looking for r'(^[0-2][0-3]:[0-5][0-9]$)'

^ denotes start of line or start of string (depending on mode)

$ denotes end of line or end of string (depending on mode)

You should use \b instead of ^ and \b instead of $, i.e.

import re
text = "Some text some text some text 12:00 Some text some text some text"
print(re.findall(r'(\b[0-2][0-3]:[0-5][0-9]\b)', text))

output

['12:00']

If you want to know more about \b read python re docs

Sign up to request clarification or add additional context in comments.

2 Comments

@MikeM re.findall returns a list of found text. The brackets in the output is the result of printing a list. Which, in this situation, happens to contain only 1 item.
@MikeM oh, you mean the opening & closing parentheses? Beats me.
0

Using (0?[1-9]|1[0-2]):[0-5][0-9] instead of (^[0-2][0-3]:[0-5][0-9]$)

2 Comments

How will that ever match, say, 23:15?
@pepoluan Above regex is used for 12 hours format, so with 24 hours format, please use ([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.