问题
I want to check if a string is a positive natural number but I don't want to use Integer.parseInt()
because the user may enter a number larger than an int. Instead I would prefer to use a regex to return false if a numeric String contains all "0" characters.
if(val.matches("[0-9]+")){
// We know that it will be a number, but what if it is "000"?
// what should I change to make sure
// "At Least 1 character in the String is from 1-9"
}
Note: the string must contain only 0
-9
and it must not contain all 0
s; in other words it must have at least 1 character in [1-9]
.
回答1:
You'd be better off using BigInteger if you're trying to work with an arbitrarily large integer, however the following pattern should match a series of digits containing at least one non-zero character.
\d*[1-9]\d*
Debuggex Demo
Debugex's unit tests seem a little buggy, but you can play with the pattern there. It's simple enough that it should be reasonably cross-language compatible, but in Java you'd need to escape it.
Pattern positiveNumber = Pattern.compile("\\d*[1-9]\\d*");
Note the above (intentionally) matches strings we wouldn't normally consider "positive natural numbers", as a valid string can start with one or more 0
s, e.g. 000123
. If you don't want to match such strings, you can simplify the pattern further.
[1-9]\d*
Debuggex Demo
Pattern exactPositiveNumber = Pattern.compile("[1-9]\\d*");
回答2:
If you want to match positive natural numbers, written in the standard way, without a leading zero, the regular expression you want is
[1-9]\d*
which matches any string of characters consisting only of digits, where the first digit is not zero. Don't forget to double the backslash ("[1-9]\\d*"
) if you write it as a Java String literal.
来源:https://stackoverflow.com/questions/24645577/regular-expression-to-check-if-a-string-is-a-positive-natural-number