Checking whether a String contains a number value in Java [closed]
Solution 1:
if(str.matches(".*\\d.*")){
// contains a number
} else{
// does not contain a number
}
Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.
Not working suggested solution
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";
System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));
Working solution
String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
System.out.println("'"+strWithNumber+"' contains digit");
} else{
System.out.println("'"+strWithNumber+"' does not contain a digit");
}
String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}
Output
'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit
Solution 2:
Using a loop -
public static boolean containsDigit(final String aString)
{
if (aString != null && !aString.isEmpty())
{
for (char c : aString.toCharArray())
{
if (Character.isDigit(c))
{
return true;
}
}
}
return false;
}
Using a stream -
public static boolean containsDigit(final String aString)
{
return aString != null && !aString.isEmpty() &&
aString.chars().anyMatch(Character::isDigit);
}
Solution 3:
Shef's answer doesn't compile for me. It looks like he's using RegEx in String.contains()
. If you want to use RegEx use this:
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string has a number";
System.out.println(strWithNumber.matches(".*\\d.*"));
System.out.println(strWithoutNumber.matches(".*\\d.*"));