#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2011
    Posts
    2
    Rep Power
    0

    How would you regex this "12345~12345~12345"?


    I have a form input I'm trying to error check with JavaScript.
    Only groups of 5 digits with a single '~' separating them.
    For example:
    Code:
     BAD 1
     BAD 12
     BAD 123
     BAD 1234
    GOOD 12345
     BAD 123456
      OK 12345~
     BAD 12345~123
    GOOD 12345~12345
     BAD 12345~12~12345
    GOOD 12345~12345~12345
    Using the Regex Powertoy the closest I came (I thought) was:
    Code:
    if(str.match(/\b[0-9]{5}\b/) && !str.match(/(\b[0-9]{0,4}\b)/)){
    I need some Regex genius to explain a solution, if any.
    Thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2007
    Posts
    1,513
    Rep Power
    1424
    I'd try something different, than the word boundary approach. I'm not entirely sure, if that works for JS, but please try, if this fits your needs:
    Code:
    /^((^|~)(\d{5}))+~?$/
    The idea is to match five figures, which follow either the start of a given string or a ~. To make your "ok case" possible, the optional ~ before the end of the given string is appended to the pattern. Unfortunately, this would allow for a string like 12345~12345~ and you didn't say, what should happen in this case.

    Regards, Jens
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2011
    Posts
    2
    Rep Power
    0
    And makes all kinds of sense, and works perfectly.
    It's logically obvious and I should have gotten it.
    I never used such an obtuse conditional system before.
    I guess, I just couldn't see the forest through the trees.

    The "OK" case was just my way of saying that didn't mater if it passed or not. I suppose I'd prefer it didn't, so I pulled "~?".

    Thanks a million.

IMN logo majestic logo threadwatch logo seochat tools logo