Java Regular Expression to Check If String contains at least One Digit

This week's task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing "abcd" to pattern should false, while passing "abcd1" to return true, because it contains at least one digit. Similarly passing "1234" should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with an inbuilt support of regular expression e.g.split method, replaceAll() and  matches method, which can be used for this purpose, but they have a drawback.  They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don't need to spend time on creating and compiling pattern, which is expensive compared to testing a String against the pattern.

For reusable patterns, you can take help of java.util.regex package, it provides two class Pattern and Matcher to create pattern and check String against that pattern.

In order to complete this, we first need to create a regular expression pattern object, we can do that by passing regular expression String "(.)*(\\d)(.)*" to Pattern.compile() method, this returns a compiled version of regular expression String. By using this pattern you can get Matcher object to see if input string passes this regular expression pattern or not.

We will learn more about our regular expression String in next section, when we will see our code example for check if String contains a number or not.




Regular Expression to Find if String contains Number or Not

Following code sample is our complete Java program to check if String contains any number or not. You can copy this code into your favourite IDE e.g. Eclipse, Netbeans or IntelliJ IDEA. Just create a Java source file with name of our public class RegularExpressionDemo and run it from IDE itself.

Alternatively you can run Java program  from command line by first compiling Java source file using javac compiler and then running it using java command.

Now let's understand core of the program, the regular expression itself. We are using "(.)*(\\d)(.)*", where dot and start are meta character used for any character and any number of timer. \d is a character class for matching digits, and since backward slash need to escaped in Java, we have put another back slash e.g. \\d..

So if you read this regular expression, it days any character any number of time, followed by any digit then again any character any number of time.  Which means this will match any String which contains any numeric digit e.g. from 0  - 9.


Regular Expression in Java for Checking if String contains Numberimport java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Java Program to show example of how to use regular expression 
 * to check if  String contains any number or  not. Instead of 
 * using matches() method of java.lang.String, we have used Pattern
 * and Matcher class to avoid creating temporary Pattern objects.
 *
 * @author http://java67.blogspot.com
 */

public class RegularExpressionDemo {

    public static void main(String args[]) {

        // Regular expression pattern to test input
        String regex = "(.)*(\\d)(.)*";      
        Pattern pattern = Pattern.compile(regex);

        Scanner reader = new Scanner(System.in);
        String input = "TEST";

       System.out.println("Please enter input, must contain at-least one digit");
       
       while (!input.equalsIgnoreCase("EXIT")) {        

            input = reader.nextLine();
           
           // Pattern pattern = Pattern.compile(regex);  // Don't do this, creating Pattern is expensive
            Matcher matcher = pattern.matcher(input);

            boolean isMatched = matcher.matches();
            if (isMatched) {
                System.out.println("PASS");

            } else {
                System.out.println("FAIL, Incorrect input");

            }
        }
    }

}


Output:
Please enter input, must contain at-least one digit
"ABC"
FAIL, Incorrect input

"ABC1"
PASS

""
FAIL, Incorrect input

"1"
PASS

"234"
PASS

"EXIT"
FAIL, Incorrect input

You can see that our pattern behaves correctly and returns true only if input contains any digit, even for empty String, it returns false because there is no number on it.

That's all on this post about How to check if a String contains numbers or any numeric digit in Java. You can use this regular expression to separate alphabetic string from alphanumeric ones. This regular expression and String example, also teaches best practices about regex. If you are checking many String against same pattern then always use same pattern object, because compilation of pattern takes more time than check if a String matches that pattern or not. Many programmer, make mistake of declaring Pattern and Matcher together, but if check input in a loop, just like we are doing in this example, it's not a wise decision, because it will create a new Pattern object, which take more time to compile.


3 comments:

  1. This is good in one locale only. It cannot be used as a generic numeric format validation, as each locale has specific requirements (e.g. decimal separator is the comma ',' in many locales)

    ReplyDelete
  2. Slightly better:

    private static final Pattern pattern = Pattern.compile("\\d");

    public static boolean hasNumber(String str)
    {
    return pattern.matcher(str).find();
    }

    ReplyDelete
  3. How do I can find if a String is numric in Java? will this work [0-9](.*) ?

    ReplyDelete