maybeStripNationalPrefixAndCarrierCode method
bool
maybeStripNationalPrefixAndCarrierCode(
- StringBuffer number,
- PhoneMetadata metadata,
- StringBuffer? carrierCode
Strips any national prefix (such as 0, 1) present in the number provided.
number
the normalized telephone number that we wish to strip any
national dialing prefix from. metadata
the metadata for the region
that we think this number is from. carrierCode
a place to insert the carrier
code if one is extracted. eturns true if a national prefix or
carrier code (or both) could be extracted.
Implementation
bool maybeStripNationalPrefixAndCarrierCode(
StringBuffer number,
PhoneMetadata metadata,
StringBuffer? carrierCode,
) {
String possibleNationalPrefix = metadata.nationalPrefixForParsing;
if (number.length == 0 || possibleNationalPrefix.isEmpty) {
// Early return for numbers of zero length.
return false;
}
// Attempt to parse the first digits as a national prefix.
Match? prefixMatcher =
RegExp(possibleNationalPrefix).matchAsPrefix(number.toString());
if (prefixMatcher != null) {
// Check if the original number is viable.
PhoneNumberDesc generalDesc = metadata.generalDesc;
bool isViableOriginalNumber =
matchNationalNumber(number.toString(), generalDesc, false);
// prefixMatcher.group(numOfGroups) == null implies nothing was captured by the
// capturing
// groups in possibleNationalPrefix; therefore, no transformation is necessary,
// and we just
// remove the national prefix.
int numOfGroups = prefixMatcher.groupCount;
String transformRule = metadata.nationalPrefixTransformRule;
if (transformRule.isEmpty || prefixMatcher.group(numOfGroups) == null) {
// If the original number was viable, and the resultant number is not, we
// return.
if (isViableOriginalNumber &&
!matchNationalNumber(number.toString().substring(prefixMatcher.end),
generalDesc, false)) {
return false;
}
if (carrierCode != null &&
numOfGroups > 0 &&
prefixMatcher.group(numOfGroups) != null) {
carrierCode.write(prefixMatcher.group(1));
}
String remainingNumber =
number.toString().replaceRange(0, prefixMatcher.end, '');
number.clear();
number.write(remainingNumber);
return true;
} else {
// Check that the resultant number is still viable. If not, return. Check this
// by copying
// the string buffer and making the transformation on the copy first.
StringBuffer transformedNumber = StringBuffer(number.toString());
String replacedFirstNumber = replaceFirstAndFormat(
number.toString(), prefixMatcher.pattern, transformRule);
transformedNumber.clear();
transformedNumber.write(replacedFirstNumber);
if (isViableOriginalNumber &&
!matchNationalNumber(
transformedNumber.toString(), generalDesc, false)) {
return false;
}
if (carrierCode != null && numOfGroups > 1) {
carrierCode.write(prefixMatcher.group(1));
}
String remainingNumber = number
.toString()
.replaceRange(0, number.length, transformedNumber.toString());
number.clear();
number.write(remainingNumber);
return true;
}
}
return false;
}