aturetsky
asked on
simplest way to check if a given string is a positive integer using regex
This seems to be simple and yet I can't find anything other than complicated expressions I found on other sites.
Basically I need a regular expression that will check if a given string is an integer 1 or above. So, for example, [1-9] would ensure that it's an integer 1 through 9. But how would I check for an integer from 1 and up?
Basically I need a regular expression that will check if a given string is an integer 1 or above. So, for example, [1-9] would ensure that it's an integer 1 through 9. But how would I check for an integer from 1 and up?
You'll probably want to make sure you don't match on a partial string too actually, so you'll need to match the start and end of the string with ^ and $ respectively:
^[1-9][0-9]*$
^[1-9][0-9]*$
ASKER
Hmm, your first solution seems to work as well and doesn't appear to match on a partial string (which is as desired). Does the need for ^ and $ depend on what language and api is being used? I am using java and am doing
inputString.matches([1-9][ 0-9]*)
and it (as desired) returns false for partial matches, so for "blah45" or "45blah" it returns false, but for "45" it returns true.
Why then would we need the begin and end characters?
inputString.matches([1-9][
and it (as desired) returns false for partial matches, so for "blah45" or "45blah" it returns false, but for "45" it returns true.
Why then would we need the begin and end characters?
this is simple you don't need regular expression. convert the string to number (if necessary, if not depending on your language will do it for you automatically), then check if its greater than 0, eg if int(string) > 0. i can't see why you need a regular expression for that simple task.
ASKER
ghostdog74: I don't want to do it via exception handling (I am using java).
You can simplify that somewhat to
boolean isPositive = s.matches("\\d+");
ASKER
CEHJ - that looks like the best solution thus far - but it doesn't exclude 0 and, as mentioned, I need 1 and up. Any thoughts?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
:-)
[1-9][0-9]*