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

    Join Date
    Jan 2012
    Posts
    9
    Rep Power
    0

    Validate number?


    I have a string with numbers, how do I write a regex so that only one of the numbers can be entered in input?
  2. #2
  3. Turn left at the third duck
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Location
    Nelson, NZ
    Posts
    112
    Rep Power
    93
    Do you mean you have a list of numbers like 124,222,39 and that your input has to be one of these numbers?
    If so the regex would look like
    Code:
    ^(?:124|222|39)$
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2012
    Posts
    9
    Rep Power
    0
    Exactly what I was looking for

    I have read about these things many times and somehow I always forget...

    Would you please explain what happens in the example?

    Thanx!
  6. #4
  7. Turn left at the third duck
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Location
    Nelson, NZ
    Posts
    112
    Rep Power
    93
    Hi Marcus,

    Originally Posted by marcushjortsber
    Would you please explain what happens in the example?
    The ^ means "match beginning of string"
    The $ means "match end of string"
    The (?: stuff ) means that the parentheses are non-capturing (otherwise the content would get captured in Group 1, which you could reference as \1 or $1. In the memory environments we operate in, it doesn't really matter, we could have used a plain (), but I find that when I get sloppy in one place I risk getting sloppy all over the place.
    The | is the classic alternation (OR) operator.
    Thus the regex engine is told to:
    Match the beginning of the string, THEN (124 OR 222 OR 39), THEN the end of the string.
    Without the beginning and end of string operators, the regex would match 39 in "39 ducks", "cloud 39" or 12398.

IMN logo majestic logo threadwatch logo seochat tools logo