Issue
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]
.
Solution
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*
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*
Pattern exactPositiveNumber = Pattern.compile("[1-9]\\d*");
Answered By - dimo414
Answer Checked By - Mary Flores (JavaFixing Volunteer)