int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
if (firstNationalNumberDigit != -1) {
rawInput = rawInput.substring(firstNationalNumberDigit);
}
}
PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
if (countryCode == NANPA_COUNTRY_CODE) {
if (isNANPACountry(regionCallingFrom)) {
return countryCode + " " + rawInput;
}
} else if (metadataForRegionCallingFrom != null &&
countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
NumberFormat formattingPattern =
chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
nationalNumber);
if (formattingPattern == null) {
// If no pattern above is matched, we format the original input.
return rawInput;
}
NumberFormat newFormat = new NumberFormat();
newFormat.mergeFrom(formattingPattern);
// The first group is the first group of digits that the user wrote together.
newFormat.setPattern("(\\d+)(.*)");
// Here we just concatenate them back together after the national prefix has been fixed.
newFormat.setFormat("$1$2");
// Now we format using this pattern instead of the default pattern, but with the national
// prefix prefixed if necessary.
// This will not work in the cases where the pattern (and not the leading digits) decide
// whether a national prefix needs to be used, since we have overridden the pattern to match
// anything, but that is not the case in the metadata to date.
return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
}
String internationalPrefixForFormatting = "";
// If an unsupported region-calling-from is entered, or a country with multiple international
// prefixes, the international format of the number is returned, unless there is a preferred
// international prefix.
if (metadataForRegionCallingFrom != null) {
String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
internationalPrefixForFormatting =
UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
? internationalPrefix
: metadataForRegionCallingFrom.getPreferredInternationalPrefix();
}
StringBuilder formattedNumber = new StringBuilder(rawInput);
String regionCode = getRegionCodeForCountryCode(countryCode);
// Metadata cannot be null because the country calling code is valid.
PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
maybeAppendFormattedExtension(number, metadataForRegion,
PhoneNumberFormat.INTERNATIONAL, formattedNumber);
if (internationalPrefixForFormatting.length() > 0) {
formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
.insert(0, internationalPrefixForFormatting);