Wednesday, April 12, 2023

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 inbuilt support of regular expression like 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 patterns, which is expensive compared to testing a String against the pattern.

For reusable patterns, you can take the 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 the input string passes this regular expression pattern or not.

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





Regular Expression to Find if String contains Number or Not

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

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

Now let's understand the core of the program, the regular expression itself. We are using "(.)*(\\d)(.)*", where dot and start are meta characters used for any character and any number of timer. \d is a character class for matching digits, and since backward slash needs to escaped in Java, we have put another backslash 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.  This 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 the input contains any digit, even for an 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 an alphabetic string from an alphanumeric one. This regular expression and String example also teaches best practices about regex

If you are checking much String against the same pattern then always use the same pattern object, because the compilation of pattern takes more time than check if a String matches that pattern or not.

Many programmers, make the 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 takes more time to compile.


10 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
    Replies
    1. Hello @Anonymous, the right way to check if a String is numeric in Java is by using a library function like isNumber() or isNumeric(). Your regular expression is ok, but it will fail if String contains + or - character e.g. -234 or +234, if the number contains points e.g. floating point numbers i.e. 101.1 etc, but its correct as far as regular expression is concerned. Even I have used similar pattern to check if String contains number or not.

      Delete
  4. how to add two string without using inbuilt library in java

    ReplyDelete
    Replies
    1. @Anonymous, this is very interesting question. I don't know the answer now, but will try to find out one. I think approach should be just to copy characters from two arrays to a bigger array.

      Delete
  5. boolean flag = true;

    try {
    Integer.valueOf(str);
    } catch (NumberFormatException nfe) {
    flag = false;
    }

    return flag;

    ReplyDelete
  6. Your regex is incorrect.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.