Check for non-numeric characters in a string

I want to check if a string contains only numeric characters or alphanumeric characters.

I have to implement this check in a database transaction, where about hundreds of thousands of records will be fetched and go through this check, so I need an optimized performance response.

I have currently implemented this with a try-catch block: I parsed a string in Integer in a try block and checked for a NumberFormatException exception in a catch block. Please suggest if I am wrong.

+5
source share
2 answers

You can verify this with a regex.

Assume that (only numerical values):

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

Assume that (alphanumeric values ​​only):

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

As Pangea said in the comments area:

If performance is critical, it prefers to compile the regular expression. The following is an example:

 String a = "dfdf4932fef84835fea"; Pattern pattern = Pattern.compile("^([A-Za-z]|[0-9])+$"); Matcher matcher = pattern.matcher(a); if (matcher.find()) { // it ok } 
+24
source

Just google, I found out this link

  public boolean containsOnlyNumbers(String str) { //It can't contain only numbers if it 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: RegExp to check the number:

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

All Articles