java regex validate and format north american phone numbers

h‮tt‬ps://www.theitroad.com

To validate and format North American phone numbers using regular expressions in Java, you can use the following regular expression pattern:

String phoneNumberPattern = "^\\(?([0-9]{3})\\)?[- ]?([0-9]{3})[- ]?([0-9]{4})$";

This regular expression pattern matches a phone number in North American format, with an optional area code in parentheses and the number separated by a hyphen or a space.

To use this regular expression to validate and format a phone number, you can use the following code:

String phoneNumber = "123-456-7890";
if (phoneNumber.matches(phoneNumberPattern)) {
    phoneNumber = phoneNumber.replaceAll(phoneNumberPattern, "($1) $2-$3");
    System.out.println("Valid phone number: " + phoneNumber);
} else {
    System.out.println("Invalid phone number: " + phoneNumber);
}

In the example above, the "phoneNumber" string is first checked if it matches the "phoneNumberPattern" regular expression. If it does, the phone number is formatted using the "replaceAll()" method and the capture groups in the regular expression pattern. The "($1) $2-$3" string is the replacement string, which formats the phone number with parentheses around the area code and a hyphen between the second and third blocks of digits.

You can modify the regular expression pattern to match different formats of North American phone numbers, and adjust the replacement string accordingly to format the phone number in the desired format.