Java String - See if a string contains only numbers and not letters

You can also use NumberUtil.isCreatable(String str) from Apache Commons


In order to simply check the string that it contains only ALPHABETS use the following code :

if (text.matches("[a-zA-Z]+"){
   // your operations
}

In order to simply check the string that it contains only NUMBER use the following code :

if (text.matches("[0-9]+"){
   // your operations
}

Hope this will help to someone!


If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).


This is how I would do it:

if(text.matches("^[0-9]*$") && text.length() > 2){
    //...
}

The $ will avoid a partial match e.g; 1B.