Regex Search Time Values

I continue to go into situations where I end up with two regular expressions to find subtle changes (for example, one script for 0-9, and the other for 10-99 because of the extra number)

I usually use [0-9] to search for single-digit strings, and then [0-9][0-9] to search for multiple-digit strings, is there a more suitable character for this?

ex. which expression would I use to search for strings simultaneously 6:45 AM and 10:52 PM

+4
source share
7 answers

You can specify a repetition with curly braces. [0-9]{2,5} corresponds to two to five digits. Therefore, you can 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 numbers, this way

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

+7
source

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

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

or for actual time:

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

If you are looking for a temporary patten, you would do something like:

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

Or for a more specific regex

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

Like other answers, except that AM / PM is not fixed, which should be more efficient

 \d{1,2}:\d{1,2}\s(?:AM|PM) 
+1
source

if I have a file containing:

1 ABC
2 123XYZ
3 6:45 a.m.
4 123DHD
5 ABC
6 10:52 p.m.
7 CDE

and follow these

 $>grep -P '6:45\sAM|10:52\sPM' temp 6:45 AM 10:52 PM $>. 

should do the trick (-P - perl regx)

EDIT:

Perhaps I misunderstood the other answers are very good if I just wanted to find the time, but you seem to be after a certain time. others will match ANY time in HH: MM format.

in general, I believe that the items you after this will | which is used in this case, so that alternative phrases and {n, m} correspond to the nth time {1,2}, correspond 1-2 times, etc.

0
source

It can check all types of time formats:

eg. 12:05PM, 3:19AM, 04:25PM, 23:52PM

 my $time = "12:52AM"; if ($time =~ /^[01]?[0-9]\:[0-5][0-9](AM|PM)/) { print "Right Time Dude..."; } else { print "Wrong time Dude"; } 

This is the regular expression you want.

  /^[01]?[0-9]\:[0-5][0-9](AM|PM)/ 
0
source

The presence of this line as input:

 Sat, 6 May 2017 02:08:08 +0000 

I did this regEx to get combinations of one or two digits:

 [0-9]*:[0-9]*:[0-9]* 
0
source

All Articles