www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] Best RegExp for matching explicitly to numbers 1-99

  1. #1
    Join Date
    Dec 2008
    Posts
    488

    resolved [RESOLVED] Best RegExp for matching explicitly to numbers 1-99

    I'm writing a regular expression to check that the value inside a string is any integer from 1-99, but it can't be negative, or zero, or contain any other characters.

    The pattern I came up with seems a little long, and I was wondering if this was the best one to use, or if I was over thinking it?:

    Code:
    regex=/^(([1-9][0-9])|([1-9]))$/;
    Last edited by jamesbcox1980; 11-10-2009 at 12:30 PM.

  2. #2
    Join Date
    Aug 2007
    Posts
    3,767
    You could use /^[1-9]\d?$/ or /^[1-9][0-9]?$/ which are the same thing.

    BTW, I originally thought you wanted to include 0, in which case you do basically the same thing. /^[1-9]?\d$/. Just though I'd mention that since I had it written anyway.

    Depending on what you are doing with this string, you could be better off to just convert it to a number, and check that way. I would definitely recommend that if you ever do any sort of calculations with it, if not, I don't think it makes a huge difference.
    Last edited by Declan1991; 11-10-2009 at 01:21 PM.
    Great wit and madness are near allied, and fine a line their bounds divide.

  3. #3
    Join Date
    Dec 2008
    Posts
    488
    The problem with converting to a number first is that I'm also checking for "0", "00", "000", and "0000" (wire sizes). Since I'm already running a test there, I'm putting this test in an else if statement. I guess if I'm finished testing for aught sizes, I can then convert to integer. This might be better so that I can still validate "01" without validating "00". But your first regexp matches perfectly, other than that.
    /^[1-9]\d?$/
    Thanks

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles