Reputation: 763
This might be clear to someone familiar with regex expressions but I am not.
Example:
String onlyNumbers = "1233444";
String numbersAndDigits = "123344FF";
if (IS_ONLY_NUMBERS(onlyNumbers))
return true;
if (IS_ONLY_NUMBERS(numbersAndDigits))
return false;
Suggestions? Is there a way to do a similar check without importing libraries?
Upvotes: 3
Views: 3745
Reputation: 62864
You can try with:
if (onlynumbers.matches("[0-9]+")
return true;
if (numbersanddigits.matches("[0-9]+")
return false;
Also, as a shortcut, you can use \\d+
instead of [0-9]+
. It's just a matter of choice which one to pick.
Upvotes: 2
Reputation: 2921
Try using String.matches("\\d+")
. If that statement returns false, then there are characters in your string that are not digits. \d
means the character must be a digit, and the +
means that every character must be a digit.
Like so:
String onlynumbers = "1233444";
String numbersanddigits = "123344FF";
System.out.println(onlynumbers.matches("\\d+")); // prints "true"
System.out.println(numbersanddigits.matches("\\d+")); // prints "false"
Upvotes: 4