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


You may try:

if (onlynumbers.matches("[0-9]+")
    return true;

if (numbersanddigits.matches("[0-9]+")
    return false;

      



Also, as a shortcut, you can use \\d+

instead [0-9]+

. It's just a matter of choice to choose.

+2


source







All Articles