Phone Number Patterns
You'll learn how to create robust regular expression patterns that validate and extract phone numbers in various real-world formats.
Understanding Phone Number Complexity
Phone numbers appear in countless formats: (555) 123-4567, 555-123-4567, +1-555-123-4567, +44 20 1234 5678. Unlike email addresses, which follow relatively consistent structure, phone numbers vary wildly by country, region, and personal formatting preference. Your regex must handle this diversity while remaining readable.
Building Flexible Phone Patterns
Think of a phone number pattern as a template with optional parts. Start simple and add complexity:
// US format: 555-123-4567
String basicPattern = "\\d{3}-\\d{3}-\\d{4}";
Pattern p1 = Pattern.compile(basicPattern);
System.out.println(p1.matcher("555-123-4567").matches()); // true
// With optional area code parentheses: (555) 123-4567 or 555-123-4567
String areaPattern = "\\(?\\d{3}\\)?[- ]?\\d{3}-\\d{4}";
Pattern p2 = Pattern.compile(areaPattern);
System.out.println(p2.matcher("(555) 123-4567").matches()); // true
// With optional country code: +1-555-123-4567
String internationalPattern = "(\\+\\d{1,3}[- ]?)?\\(?\\d{3}\\)?[- ]?\\d{3}-\\d{4}";
Pattern p3 = Pattern.compile(internationalPattern);
System.out.println(p3.matcher("+1-555-123-4567").matches()); // true
Notice how \\(? and \\)? make parentheses optional, [- ]? allows various separators, and (\\+\\d{1,3}[- ]?)? handles optional country codes. Each piece addresses a real-world variation.
Extracting Components with Groups
String pattern = "(\\+\\d{1,3}[- ]?)?(\\(?(\\d{3})\\)?[- ]?)(\\d{3})[- ]?(\\d{4})";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher("+1 (555) 123-4567");
if (m.matches()) {
System.out.println("Country: " + m.group(1)); // +1
System.out.println("Area: " + m.group(3)); // 555
System.out.println("Prefix: " + m.group(4)); // 123
System.out.println("Number: " + m.group(5)); // 4567
}
Key Takeaway: Phone number patterns require balancing flexibility (optional country codes, various separators) with capturing groups to extract meaningful components like area codes and country prefixes.