JAVA_CAT
JAVA_CAT

Reputation: 859

Regex to validate the length of digits in java

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"
              )
            );
          }
}

Upvotes: 1

Views: 199

Answers (2)

anubhava
anubhava

Reputation: 785176

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

Upvotes: 4

Anubhav Sharma
Anubhav Sharma

Reputation: 533

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"
                  )
                );
              }

Upvotes: 1

Related Questions