// Note getRegionCodeForCountryCode() is used because formatting information for regions which
// share a country calling code is contained by only one region for performance reasons. For
// example, for NANPA regions it will be contained in the metadata for US.
String regionCode = getRegionCodeForCountryCode(countryCallingCode);
// Metadata cannot be null because the country calling code is valid
PhoneMetadata metadata =
getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
StringBuilder formattedNumber = new StringBuilder(20);
NumberFormat formattingPattern =
chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
if (formattingPattern == null) {
// If no pattern above is matched, we format the number as a whole.
formattedNumber.append(nationalSignificantNumber);
} else {
NumberFormat numFormatCopy = new NumberFormat();
// Before we do a replacement of the national prefix pattern $NP with the national prefix, we
// need to copy the rule so that subsequent replacements for different numbers have the
// appropriate national prefix.
numFormatCopy.mergeFrom(formattingPattern);
String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
if (nationalPrefixFormattingRule.length() > 0) {
String nationalPrefix = metadata.getNationalPrefix();
if (nationalPrefix.length() > 0) {
// Replace $NP with national prefix and $FG with the first group ($1).
nationalPrefixFormattingRule =
NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
nationalPrefixFormattingRule =