I build a pattern match for the following time formats 4:05am or 11:03pm
it works on rubular but irb does not find a match. How can I fix it?
irb(main):568:0> "4:00am" =~ /[\d :\d{2}(a|p)m]/
=> 0
CodePudding user response:
As noted in comments, you have put your regex in brackets which indicate a character class. Easy enough to fix.
irb(main):001:0> "4:00am" =~ /\d :\d{2}(a|p)m/
=> 0
But this would also work for:
irb(main):002:0> "4:70am" =~ /\d :\d{2}(a|p)m/
=> 0
Instead you may want to specify that the :
can be followed by the digits 0-5 and then by any digit.
irb(main):005:0> "4:50am" =~ /\d :[0-5]\d(a|p)m/
=> 0
irb(main):006:0> "4:70am" =~ /\d :[0-5]\d(a|p)m/
=> nil
But this can still detect a crazy time like "14:40am"
. Given that it picks up on AM/PM, we can assume a 12 hour clock and modify your regular expression still further:
irb(main):009:0> "14:40am" =~ /^(\d|1[0-2]):[0-5]\d(a|p)m$/
=> nil
irb(main):010:0> "12:40am" =~ /^(\d|1[0-2]):[0-5]\d(a|p)m$/
=> 0