homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Help with regex - please.

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

hi all,

I have a regex string:
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:

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?




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

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.

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



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

[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

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)

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 "?".



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

Yes, if you want multiple spaces, or none, then
\s* is fine.
Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved