9

I want to check whether the String contains only numeric characters or it contains alpha-numeric characters too.

I have to implement this check in database transaction where about a hundred-thousand records are going to be fetched and passed through this check, so I need optimized performance answer.

Currently, I have implemented this through a try-catch block: I parsed the string in Integer in try block and checked for the NumberFormatException in the catch block. Please suggest if I'm wrong.

halfer
  • 19,824
  • 17
  • 99
  • 186
HarsH
  • 760
  • 3
  • 12
  • 27

2 Answers2

31

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
}
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
  • 5
    Since performance is of main concern i suggest compiling the regex once and reuse http://stackoverflow.com/questions/1720191/java-util-regex-importance-of-pattern-compile – Aravind Yarram Sep 30 '11 at 07:39
  • I suggest OP do a benchmark between the regex option and commons-lang's StringUtils.isNumeric(), isAlpha() using google caliper http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java/4480774#4480774 – Aravind Yarram Sep 30 '11 at 07:42
  • @HarsH If your data contains lot of duplicates then you can try caching the outcome of the comparision against input and then change the logic to first do a lookup before the check. you can either handcode all this or use a ComputingMap (http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) from guava – Aravind Yarram Sep 30 '11 at 07:53
  • @Pangea Thanks for the suggestion, but i won't be needing this, since the data would be of usernames and that would be unique always. – HarsH Sep 30 '11 at 09:15
8

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+)?");
Jean-Charles
  • 1,690
  • 17
  • 28
  • Will this approach be an optimized one, with loop for all the characters in the string and also to be executed for around 1Lakh records ? – HarsH Sep 30 '11 at 07:40
  • 3
    Warning! [`isDigit()`](http://download.oracle.com/javase/7/docs/api/java/lang/Character.html#isDigit(char)) is *not just* 0-9! – Joachim Sauer Sep 30 '11 at 07:40