Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

regular expression for "time-of-day" is not working

by vjvalor (Initiate)
on Apr 05, 2012 at 09:37 UTC ( [id://963628]=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://963628]
Approved by Happy-the-monk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-03-28 14:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found