Check if a string contains a number using Java
By Steve Claridge on 2017-08-28.
I was writing a search box that needed to determine the data type that the user was searching against. So if they entered a search term containing a number then they were searching for an ID, otherwise they were searching for a name. So I needed to check if the search string contained at least one number. Simple regex did the job.
public boolean stringContainsNumber( String s )
{
Pattern p = Pattern.compile( "[0-9]" );
Matcher m = p.matcher( s ); return m.find();
}
You could make this in to a one-line if you wanted
public boolean stringContainsNumber( String s )
{
return Pattern.compile( "[0-9]" ).matcher( s ).find();
}
And here are some quick tests to see it working
System.out.println( stringContainsNumber( "Hello World!" ) ); //false
System.out.println( stringContainsNumber( "Hello W0rld!" ) ); //true
System.out.println( stringContainsNumber( "1" ) ); //true
System.out.println( stringContainsNumber( "a" ) ); //false
System.out.println( stringContainsNumber( "2982039832908" ) ); //true
System.out.println( stringContainsNumber( "sssqsqsqsqsqsqsqs1" ) ); //true
System.out.println( stringContainsNumber( "" ) ); //false
System.out.println( stringContainsNumber( null ) ); //throws exception
You will need to decide yourself how you treat a null string passed as the search parameter. Currently this method will throw a NullPointerException.