Meyyappan Meyyappan - 2 months ago 4x
Python Question

How to extract time from string in python using pattern matching?

An example of the python string is

'8:30 AM- 10:00 PM Subject: Math'
. In general, the string contains a start time, end time, and the subject I want to separate this string into 3 components: the start time, end time, and subject. For example
8:30 AM
10:00 PM
, and
Subject: Math

How can I do this using regex in python?


You can use re.split() using a positive lookbehind to AM or PM having an optional - and a space character as a delimiter:

>>> import re
>>> s = "8:30 AM- 10:00 PM Subject: Math"
>>> re.split(r"(?<=AM|PM)-?\s", s)
['8:30 AM', '10:00 PM', 'Subject: Math']