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