Check if string contains any non-digit character - no libraries - Java
This might be clear to someone familiar with regex expressions, but I'm not sure.
Example (let me clarify this: THIS IS AN EXAMPLE):
String onlynumbers = "1233444";
String numbersanddigits = "123344FF";
if ( onlynumbers IS_ONLY_NUMBERS())
return true;
if ( numbersanddigits IS_ONLY_NUMBERS())
return false;
Suggestions? Is there a way to do a similar check without importing libraries?
+3
source to share
2 answers
Try to use String.matches("\\d+")
. If this statement returns false, then the string contains characters that are not numbers. \d
means that a character must be a digit, and +
means that each character must be a digit.
Same:
String onlynumbers = "1233444";
String numbersanddigits = "123344FF";
System.out.println(onlynumbers.matches("\\d+")); // prints "true"
System.out.println(numbersanddigits.matches("\\d+")); // prints "false"
+4
source to share