Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex find time values

I keep getting into situations where I end up making two regular expressions to find subtle changes (such as one script for 0-9 and another for 10-99 because of the extra number)

I usually use [0-9] to find strings with just one digit and then [0-9][0-9] to find strings with multiple digits, is there a better wildcard for this?

ex. what expression would I use to simultaneously find the strings 6:45 AM and 10:52 PM

like image 679
CQM Avatar asked Jun 07 '11 15:06

CQM


People also ask

Which regex pattern can be used to find the time?

regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; Where: ( represents the start of the group. [01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.

How does regular expression validate time in 24 hour format?

In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.

How does regular expression validate time in 12 hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

Can you use regex in PostgreSQL?

The Regular Expressions in PostgreSQL are implemented using the TILDE (~) operator and uses '. *” as a wildcard operator. As you can see in the figure above, we have used Regular Expression in PostgreSQL using the TILDE (~) operator and the wildcard '.


2 Answers

You can specify repetition with curly braces. [0-9]{2,5} matches two to five digits. So you could use [0-9]{1,2} to match one or two.

[0-9]{1,2}:[0-9]{2} (AM|PM)

I personally prefer to use \d for digits, thus

\d{1,2}:\d{2} (AM|PM)

like image 141
Wiseguy Avatar answered Oct 15 '22 11:10

Wiseguy


[0-9] 1 or 2 times followed by : followed by 2 [0-9]:

[0-9]{1,2}:[0-9]{2}\s(AM|PM)

or to be valid time:

(?:[1-9]|1[0-2]):[0-9]{2}\s(?:AM|PM)
like image 25
manji Avatar answered Oct 15 '22 09:10

manji