http://www.perlmonks.org?node_id=963628

vjvalor has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks,

My regular expression for time-of-day is not working as expected.

Regular expression below is matching "99:02 pm" which is incorrect. What went wrong?

@a = ("9:17 am", "12:30 pm", "99:02 pm", "99:99 pm"); foreach $i (@a) { print "$i\n" if($i =~ /(1[012]|[1-9]):([0-5][0-9]).([aApP][mM])/); }

Replies are listed 'Best First'.
Re: regular expression for "time-of-day" is not working
by moritz (Cardinal) on Apr 05, 2012 at 09:43 UTC
    The regex matches 9:02 pm, and since you haven't anchored it, the regex match comes out true even if it didn't match the whole string. Use at least a word boundary:
    /\b(1[012]|[1-9]):([0-5][0-9]).([aApP][mM])\b/

    See perlretut and perlre for more details.

      Thank you moritz.
Re: regular expression for "time-of-day" is not working
by DrHyde (Prior) on Apr 05, 2012 at 09:58 UTC
    It's got other problems too. It won't match "09:02" or "23:02" or "00:02". You probably want something like this ...
    /\b ( ( ([01][0-9]|2[0123]):[0-5][0-9] ) |( (1[012]|[1-9] ):[0-5][0-9]\s+[ap]m ) ) \b/ix
      Thanks you DrHyde. I was interested in 12-hour time format with no preceding 0.
Re: regular expression for "time-of-day" is not working
by choroba (Cardinal) on Apr 05, 2012 at 09:43 UTC
    Your regular expression is missing ^ ath the start and $ at the end.
Re: regular expression for "time-of-day" is not working
by Anonymous Monk on Apr 05, 2012 at 18:54 UTC