Monday, August 9, 2021

How to check if a String is Number in Java - Regular Expression Example

Regular Expression to check numeric String
In order to build a regular expression to check if String is a number or not or if String contains any non-digit character or not you need to learn about character set in Java regular expression, Which we are going to see in this Java regular expression example. No doubt Regular Expression is a great tool in a developer's arsenal and familiarity or some expertise with regular expression can help you a lot. Java supports regular expression using java.util.regex.Pattern and java.util.regex.Matchter class, you can see a dedicated package java.util.regex for a regular expression in Java. Java supports regex from JDK 1.4, which means well before Generics, Enum, or Autoboxing.

If you are writing server-side code in Java programming language then you may be familiar with the importance of regular expression which is key in parsing certain kinds of messages e.g. FIX Messages used in Electronic trading. 

In order to parse Repeating groups in FIX protocol you really need an understanding of regular expression in Java. Any way In order to learn validating numbers using regular expression we will start with a simple example


1) Check if a String is a number or not using regular expression

to clarify the requirement, a String would be a number if it contains digits. we have omitted decimal point and sign or + or - for simplicity.

If you are familiar with a predefined character class in Java regular an expression that you must know that \d will represent a digit (0-9) and \D will represent a non-digit (anything other than 0 to 9). Now using this predefined character class, a String will not be a number if it contains any non digit characters, which can be written in Java regular expression as:



Pattern pattern = Pattern.compile(".*\\D.*");

which checks for non digit character anywhere in the String. This pattern return true if String contains any thing other than 0-9 digit, which can be used to know if an String is number or not using regular expression.

Same regular expression for checking String for numbers can also be written without using predefined character set and using character class and negation as shown in following example :

Pattern pattern = Pattern.compile(".*[^0-9].*");

This is similar to the above regex pattern, the only difference is \D is replaced by [^0-9]. By the way, there are always multiple ways to check for certain things using regex.

2. Verify if a String is a six-digit number or not using regular expression

This is a kind of special regular expression requirement for validating data like id, zipcode or any other pure numerical data. In order to check for digits you can either use character class [0-9] or use short-form \d. here is a simple regular expression in Java which can check if a String contains 6 digits or not:

Pattern digitPattern = Pattern.compile("\\d\\d\\d\\d\\d\\d");

above pattern checks each character for digit six times. This pattern can also be written in much shorter and readable format as :

Pattern digitPattern = Pattern.compile("\\d{6}");

where {6} denote six times. you can also replace \d with character class [0-9] and it should work. You can further see these Java Regular expression courses to learn more about different regular expression patterns. 

Code Example - Regular expression in Java to check numbers

Java Regular Expression Example to check if String contains numbersHere is a complete code example in Java programming language to check if a String is an integer number or not. In this Java program, we are using regular expressions to check if String contains only digits i.e. 0 to 9 or not. If String only contains a digit then its number otherwise it's not a numeric String. 

One interesting point to note is that this regular expression only checks for integer numbers as it not looking for dot(.) characters, which means floating point or decimal numbers will fail this test.


import java.util.regex.Pattern;
/**
 * Java program to demonstrate use of Regular Expression to check
 * if a String is a 6 digit number or not.
 */

public class RegularExpressionExample {
 
    public static void main(String args[]) {
     
        // Regular expression in Java to check if String is a number or not
        Pattern pattern = Pattern.compile(".*[^0-9].*");
       //Pattern pattern = Pattern.compile(".*\\D.*");
       String [] inputs = {"123", "-123" , "123.12", "abcd123"};
     
       for(String input: inputs){
           System.out.println( "does " + input + " is number : "
                                + !pattern.matcher(input).matches());
       }
     
       // Regular expression in java to check if String is 6 digit number or not
       String [] numbers = {"123", "1234" , "123.12", "abcd123", "123456"};
       Pattern digitPattern = Pattern.compile("\\d{6}");       
       //Pattern digitPattern = Pattern.compile("\\d\\d\\d\\d\\d\\d");
       

       for(String number: numbers){
           System.out.println( "does " + number + " is 6 digit number : "
                               + digitPattern.matcher(number).matches());
       }
    }
 
}

Output:
does 123 is number : true
does -123 is number : false
does 123.12 is number : false
does abcd123 is number : false

does 123 is 6 digit number : false
does 1234 is 6 digit number : false
does 123.12 is 6 digit number : false
does abcd123 is 6 digit number : false
does 123456 is 6 digit number : true

That's all on using Java regular expression to check numbers in String. As you have seen in this Java Regular Expression example that it's pretty easy and fun to do the validation using regular expression.


Other Java tutorials you may find useful

17 comments:

  1. Nice information indeed. But, if your application is small and you don't use pattern matching very frequently, String class's matches() method is a shortcut for above.

    //Java docs
    public boolean matches(String regex) {
    return Pattern.matches(regex, this);
    }

    Please correct me if i am wrong.

    ReplyDelete
  2. Hello Javin, Can you please share How to ignore certain digits from any number e.g. I want to ignore only non zero digits, please suggest?

    ReplyDelete
  3. How about this solution:
    public static boolean isDigit(char c){
    int x=(int)c-(int)'0';
    if(x<0||x>9){
    return false;
    }
    return true;

    }

    public static boolean isOnlyDigit(String s){

    for(int i=0;i<s.length();i++){
    if(!isDigit(s.charAt(i))){
    return false;
    }
    }
    return true;
    }

    public static void main(String[] args) {
    String s="098234";
    System.out.println(isOnlyDigit(s));


    }

    ReplyDelete
  4. public boolean containsOnlyDigits(String s) {

    if (s.isEmpty()) return false;

    for (int i = 0; i < s.length(); i++) {
    char temp = s.charAt(i) - '0';
    if (temp < 0 || temp > 9)
    return false;
    }

    return true;
    }

    ReplyDelete
  5. Scanner scn = new Scanner(System.in);
    boolean flag = false;
    System.out.println("Enter digits");
    try {
    Integer i = scn.nextInt();
    } catch(InputMismatchException ie) {
    flag = true;
    }
    if(!flag) {
    System.out.println("All are digits");
    } else {
    System.out.println("All entries are not digit");
    }
    }

    ReplyDelete
  6. I have query
    I want to give input like this {25,45} using array is it possible. for the main function i need to use numbers only.

    ReplyDelete
  7. @Anonymous, it's not possible to give a Java program input like that i.e. {25, 45}, though you can write little bit code to achieve that. Since that is String, just write a parser which reads this string, split it and create an array of String. Alternatively, you can also check this post to learn how to pass array as input to Scanner.

    ReplyDelete
  8. Your regex is incorrect. It should be ".*^[0-9]*." rather than ".*^[0-9].*"

    ReplyDelete
  9. private static void checkStringContainsOnlyDigits(String string) {
    try{
    Double doub = Double.parseDouble(string);
    System.out.println(doub);
    } catch(NumberFormatException e){
    System.out.println(" given string is alpha numeric");
    }


    }

    ReplyDelete
  10. public static bool IsDigit(string strIsDigit)
    {

    foreach(char c in strIsDigit)
    {
    if (c < 48 || c > 57)
    return false;
    }
    return true;
    }

    ReplyDelete
  11. public class Number {
    public static void main(String [] args){
    String s ="123a45";
    int count =0;
    for(int i=0;i<s.length();i++){
    if(Character.isDigit(s.charAt(i))){
    count++;
    }
    }
    if(count==s.length()){
    System.out.println("The given string is numeric");
    }else{
    System.out.println("The given string is not numeric");
    }
    }
    }

    ReplyDelete
  12. package String;

    public class Numberstrig {
    public static void main(String [] args){
    String s ="12345";
    if(s.matches("[0-9]+")){
    System.out.println("The given string is an numeric string");
    }else{
    System.out.println("The given string is not a numeric string");
    }
    }
    }

    ReplyDelete
  13. -123 is also number but it returns false, how to handled it

    ReplyDelete
    Replies
    1. Change in the regular expression in 0 to 9

      Delete
  14. private static boolean onlyDigits(String s) {
    String regex = "[0-9]";
    return (s.replaceAll(regex, "").length() == 0);
    }

    ReplyDelete
  15. I don't no whats the correct structure of this program

    ReplyDelete
  16. public static void main(String[] args) {
    String strNumber = "123456";
    try{
    long number = Long.parseLong(strNumber);
    System.out.println("It is a number:-"+number );
    }catch (NumberFormatException|NullPointerException e){
    System.out.println("It is not a number");
    }


    }

    ReplyDelete