mw <mw*******@gmail.comwrites:
I am trying to make a regex for a 12 hour clock, and I can't seem to
get it just right.
What I have now is
var regexmatch = /(1[012]:[0-5][0-9]|[1-9]:[0-5][0-9])\s((a\.m\.)|(p
\.m\.))/i
Seems about right. You can make it a little more compact by not
repeating the pattern for minutes, and you have capture groups for
both a.m., p.m. and the alternative. You might want to use a
non-capturing parentheses for one of them (or all, if you don't use
the captured groups at all).
The actual problem is that you haven't anchored the expression, so
it can match a sub-string of the string you use it on. I.e.,
it matches "23:13 p.m." because it matches the substring "3:13 p.m.".
I.e., something like /^((?:1[012]|[1-9]):[0-5][0-9])\s([ap]\.m\.)$/i.
If you do want to match substrings of longer strings, then you can't
use "^" and "$" as anchors. Instead you can start with a "\b" assertion
(i.e., the character before the first digit was not a word character):
/\b((?:1[012]|[1-9]):[0-5][0-9])\s([ap]\.m\.)/ig
Or, if you only want to check the format, not try to parse it,
you can do away with capturing parentheses altogether.
For total compactness and (my preferences for) readabiliy:
/^(?:[1-9]|1[0-2]):[0-5]\d\s[ap]\.m\.$/i
then the tricky part where I'm pretty sure the bug is: the a.m. or
p.m.
Don't think so. It seems to do what you want it to ...
I think it is my inexperience with the () that is messing this
up. I've tried all sorts of variations for the last part, but I am
stuck.
.... byut you do have an awful lot of parentheses. Only have capturing
groups "("..")" when you actually want to extract the submatch later,
and use non-capturing ones "(?:"..")" when you just want to group
parts of the expression (like parentheses in mathematics).
I keep ending up with expressions that are too liberal and
will allow times like 23:23 p.m. through.
That's due to not anchoring. You correctly match "3:23 p.m." in that
string.
Please excuse my slow- learning of the subject as tonight is the
first time I've touched regex in js and really regex at all.
Then you are doing really well. Trust me, I've seen lots worse. :)
Also, I'm sorry for the a.m.
p.m. part. It has gone from OK looking to ugly parenthesis nightmare
in my attempts to make it work correctly. (I've tried other without
() versions, etc, but can't seem to hit it correctly)
Maye it's because you are trying to fix a problem that is really in
another part of the expression. :)
/L
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'