Check non-numeric characters in string

You can check this with a regex.

Suppose that (numeric values only):

String a = "493284835";
a.matches("^[0-9]+$"); // returns true

Suppose that (alphanumeric values only):

String a = "dfdf4932fef84835fea";
a.matches("^([A-Za-z]|[0-9])+$"); // returns true

As Pangea said in the comments area :

If the performance are critical, it's preferrable to compile the regex. See below for an example :

String a = "dfdf4932fef84835fea";
Pattern pattern = Pattern.compile("^([A-Za-z]|[0-9])+$");
Matcher matcher = pattern.matcher(a);

if (matcher.find()) {
    // it's ok
}

Just Googling, I found out this link

 public boolean containsOnlyNumbers(String str) {        
        //It can't contain only numbers if it's null or empty...
        if (str == null || str.length() == 0)
            return false;

        for (int i = 0; i < str.length(); i++) {

            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
                return false;
        }

        return true;
    }

Edit: A RegExp to check numeric should be :

return yourNumber.matches("-?\\d+(.\\d+)?");

Tags:

Java

Regex