Regex to extract time (e.g. 7:30pm, 8 pm, 9.05) from string
regex
Solution
Perhaps something like this:
^[01]?[0-9]([:.][0-9]{2})?(\s?[ap]m)?$
Demonstration
Note that this will not handle 24-hour time, and it's not that specific about 12-hour time—i.e. it would match `19pm`.
If you want to be more specific, you might try:
^((0?[0-9]|1[012])([:.][0-9]{2})?(\s?[ap]m)|([01]?[0-9]|2[0-3])([:.][0-9]{2})?)$
Demonstration
Or to try to match it as part of a larger portion of text, you might use something like this:
\b((0?[1-9]|1[012])([:.][0-5][0-9])?(\s?[ap]m)|([01]?[0-9]|2[0-3])([:.][0-5][0-9]))\b
Demonstration
Problem
I'm working on a Rails application which uses an external feed for some event data and annoyingly they only provide a string with the time in. For example: Doors open at 7:30pm, show starts at 9pm I'm aiming to extract the first time from these strings and put it into a datetime field. The system needs to capture the following kinds of values: - 11 am - 12pm - 1pm - 2:15pm - 3.30pm - 4.45 - 5:30 - 06:15 - 07:30pm - 8:30 pm - 9.15 pm But not these ones: - 105 - 2 50 - 305pm - 4 15pm - 74pm - 840am I figure the best way to do this is with regex and through some searching (and particularly this SO question) I've got the following: `[0-9]{1,2}(:|.)??[0-9]{0,2}\s?(am|pm|AM|PM)` It partly works but doesn't exclude any of the ones I don't want and seems to only capture the first character of am/pm in 2 and 3. Is this possible with regex? Thanks!