Home > database >  Regex to validate the length of digits in java
Regex to validate the length of digits in java

Time:11-01

I am trying validate phone number. The expected valid phone numbers are 1 1234567890 , 123 1234567890, 1 1234534 etc. No brackets and white space after the country code. I wrote regex something like below. But not working as expected. Any help would be appreciated.

public class ValidatePhoneNumbers {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
            checkNumber(" 5555555555");// not a valid
            checkNumber(" 123 1234567890");//should be valid
            checkNumber(" 1 1234567890");//should be valid
            checkNumber(" 1 12345678905555");//should not be valid

    }

     protected static void checkNumber(String number) {
            System.out.println(number   " : "   (
              Pattern.matches("\\ \\d{1,3}[ ] [0-9]{1,10}$", number) 
                ? "valid" : "invalid"
              )
            );
          }
}

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this regex:

^\ (?:\d|\d{3}) \d{1,10}$

In Java:

final String regex = "^\\ (?:\\d|\\d{3}) \\d{1,10}$";

RegEx Demo

RegEx Details:

  • ^: Start
  • \ : Match
  • (?:\d|\d{3}): Match single digit or 3 digits
  • \d{1,10}: Match 1 to 10 digits
  • $: End

CodePudding user response:

Try below Just removed extra space from your regex and added few more test cases.

public static void main(String[] args) {
            // TODO Auto-generated method stub
            
                checkNumber(" 5555555555");// not a valid
                checkNumber(" 123 1234567890");//should be valid
                checkNumber(" 1 1234567890");//should be valid
                checkNumber(" 1 12345678905555");//should not be valid
                checkNumber("1234567890");
                checkNumber("91 1234567890");
                checkNumber("1 1234567890");
                checkNumber("1  1234567890");
                checkNumber(" 8239 1234567890");

        }

         protected static void checkNumber(String number) {
                System.out.println(number   " : "   (
                  Pattern.matches("\\ \\d{1,3}[ ][0-9]{1,10}$", number) 
                    ? "valid" : "invalid"
                  )
                );
              }
  • Related