extractPhoneNumber method

Map<String, String> extractPhoneNumber()

Extracts the country code and phone number from a formatted string.

Returns:

A Map<String, String> with:

  • "countryCode" → The extracted country code (e.g., +1, +91, etc.).
  • "number" → The extracted local phone number.

If the input does not match the expected phone number format, an empty map {} is returned.


Example Usage:

String phone1 = "+911234567890";
var extracted1 = phone1.extractPhoneNumber;
print(extracted1); // { "countryCode": "+91", "number": "1234567890" }

String phone2 = "9876543210"; // No country code
var extracted2 = phone2.extractPhoneNumber;
print(extracted2); // { "countryCode": "", "number": "9876543210" }

String phone3 = "+12025550123"; // US number
var extracted3 = phone3.extractPhoneNumber;
print(extracted3); // { "countryCode": "+1", "number": "2025550123" }

String invalidPhone = "12-345-678";
var extractedInvalid = invalidPhone.extractPhoneNumber;
print(extractedInvalid); // {}

Edge Cases:

  • Supports international formats like +91XXXXXXXXXX, +12025550123, etc.
  • Handles numbers without country codes, returning an empty string for "countryCode".
  • Returns {} for invalid formats, such as containing letters, dashes, or special characters.

Implementation

Map<String, String> extractPhoneNumber() {
  final match = RegExp(r'^(\+?\d{1,3})?([\d]{10,15})$').firstMatch(this);
  if (match == null) return {};
  return {
    'countryCode': match.group(1) ?? '',
    'number': match.group(2) ?? '',
  };
}