SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex that will allow a 1 or 2-digit number

    Hello,

    Right now I use this regular expression: /^\d{2}$/

    As I understand it, it will match a two digit number that begins and ends with a number, like "24", "55", "39" and "10".

    Right now, I'm trying to expand this to allow both 1 and 2-digit numbers that also begins and ends with a number.

    So numbers like "3", "7", "12" and "45".

    Would I use something like /^\d{1|2}$/

    Thanks

  2. #2
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    /^\d{1,2}$/

    You separate the upper and lower bounds with a comma.

  3. #3
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Unless the digits are part of a larger expression it would be easier just to check if the number is less than 100.

  4. #4
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The value is part of a larger expression, so the comma for the upper and lower values works great.

    Thanks both of you!

  5. #5
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As I'm working through this form, I now come across a new problem.

    Originally I just needed an expression that allowed for exactly only five numerical digits. This worked great /^\d{5}$/

    But now, I need an expression that allows for exactly only five numerical digits OR exactly only nine numerical digits.

    So now that the numbers aren't next to each other, I don't know what to do.

    /^\d{5,9}$/ won't work, because six, seven, or eight digit numbers just won't work.

    Thanks for any help.

  6. #6
    Floridiot joebert's Avatar
    Join Date
    Mar 2004
    Location
    Kenneth City, FL
    Posts
    823
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One of theese two.
    Code:
    /^\d{5}$|^\d{9}$/
    
    /^\d{5}(\d{4})?$/
    I like the second myself, because I can determine which one it is by the existance of a back reference.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •