Welcome to WebmasterWorld Guest from 54.211.17.91

Forum Moderators: open

Message Too Old, No Replies

Help with regex - please.

   
5:48 pm on Nov 26, 2012 (gmt 0)

5+ Year Member



hi all,

I have a regex string:
"/^(1[012]|[1-9])[aA|pP][mM]\s-\s(1[012]|[1-9])[aA|pP][mM]$/i"
that allows a 12 hour time duration (start - end) in the format "hh(am/pm) - hh(am/pm)". ex: "8am - 12pm".

I have been trying to modify it to allow either "8am" or "8am - 12pm" by surrounding the "end" regex with "()?" but i can't seem to get it to work. Here is the modification:
"/^(1[012]|[1-9])[\s|][aA|pP][mM](\s-\s(1[012]|[1-9])[\s|][aA|pP][mM])?$/i"


I also want to allow for a space or not between the hour and the am/pm. ex: "8am" or "8 am", but "[\s|]" does not work either.

Where am i going wrong?

thanks.
6:34 pm on Nov 26, 2012 (gmt 0)

5+ Year Member



Never mind... i got it!

It should look like: "/^(1[012]|[1-9])\s*[aA|pP][mM]\s*(-\s*(1[012]|[1-9])\s*[aA|pP][mM])?$/i"

this will allow zero or more spaces between the...

1. starting hour and am/pm
2. starting am/am and "-"
3. "-" and the ending hour
4. ending hour and am/pm

and also allow lower or upper case am/am.

Question...
Is it possible to add some regex to allow but still collapse zero or multiple spaces between items 1 tru 4 into one space?

thanks.
8:37 pm on Nov 26, 2012 (gmt 0)

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



[aA] allows both cases, but so does the /i flag.

[a|p] is "a" or "pipe" or "p". You need [ap] here.

You don't need a group for [m]. It's a literal.

Simplifies to
"/^(1[012]?|[2-9])\s?[ap]m\s?(-\s?(1[012]?|[2-9])\s?[ap]m)?$/i"


Having found the "1" once, there's no need to backtrack to find it again when the 1 isn't followed by 0, 1 or 2.
9:05 pm on Nov 26, 2012 (gmt 0)

5+ Year Member



g1smd,
Yes your modification is simpler - thanks. However, I'd like to offer a little error free flexibility in allowing the user to mistakenly enter zero or "more" spaces between items 1 tru 4 in my post as apposed to only allowing zero or "one" space. So I'll keep the "*" after the "\s" instead of "?".

Thanks.
9:27 pm on Nov 26, 2012 (gmt 0)

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



Yes, if you want multiple spaces, or none, then
\s*
is fine.