'Is there a way to fix this regex for splitting phone numbers?

Well, a beginner here... I have this regex for Pattern.compile:

Pattern pattern = Pattern.compile("^(?:\\+?(\\d{1,3}))?[- ]?(\\d{1,3})?[- ]?(\\d{4,10})$");

It is supposed to match these kinds of phone numbers:

  1. +1 234 5678900 // This is how you dial internationally
  2. +1-234-5678900 // ...
  3. 001 234 5678900 // This is how you dial internationally using 00 instead of +
  4. 001-234-5678900 // ...
  5. 0234 5678900 // This is how you dial in the same country
  6. 0234-5678900 // ...
  7. 5678900 // This is how you dial in the same area

Now it matches and correctly splits the first four but when it comes to options 5, 6 & 7 I get this:

  • Country Code: 0234
  • Local Area Code : 567
  • Number : 8900

And this:

  • Country Code: 567
  • Local Area Code: null
  • Number: 8900

What am I doing wrong or missing?

The full code:

public static void main(String[] args) {

        String phoneNumber = "+1 234 5678900";
        Pattern p = Pattern.compile("^(?:\\+?(\\d{1,4}))?[- ]?(\\d{1,3})?[- ]?(\\d{4,10})$");
        Matcher m = p.matcher(phoneNumber);

        while (m.find()) {
            printMatch("Country Code", m, 1);
            printMatch("Local Area Code", m, 2);
            printMatch("Number", m, 3);
        }
        
    }

    public static void printMatch(String label, Matcher m, int group) {
        System.out.printf("%-16s: %s%n", label, m.group(group));
    }

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source