formatNsnUsingPattern method

String formatNsnUsingPattern(
  1. String nationalNumber,
  2. NumberFormat formattingPattern,
  3. PhoneNumberFormat numberFormat, [
  4. String? optCarrierCode,
])

Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place.

nationalNumber a string of characters representing a phone number. formattingPattern the formatting rule the phone number should be formatted into. numberFormat the format the phone number should be formatted into. optCarrierCode

Implementation

String formatNsnUsingPattern(String nationalNumber,
    NumberFormat formattingPattern, PhoneNumberFormat numberFormat,
    [String? optCarrierCode]) {
  String numberFormatRule = formattingPattern.format;
  String formattedNationalNumber = '';
  RegExp patternToMatch = RegExp(r'' + formattingPattern.pattern);

  if (numberFormat == PhoneNumberFormat.national &&
      optCarrierCode != null &&
      optCarrierCode.isNotEmpty &&
      formattingPattern.domesticCarrierCodeFormattingRule.isNotEmpty) {
    // Replace the $CC in the formatting rule with the desired carrier code.
    String carrierCodeFormattingRule =
        formattingPattern.domesticCarrierCodeFormattingRule;
    carrierCodeFormattingRule =
        carrierCodeFormattingRule.replaceAll(_ccString, optCarrierCode);
    // Now replace the $FG in the formatting rule with the first group and the
    // carrier code
    // combined in the appropriate way.
    numberFormatRule = numberFormatRule.replaceFirst(
        firstGroupPattern, carrierCodeFormattingRule);
    formattedNationalNumber =
        replaceAllAndFormat(nationalNumber, patternToMatch, numberFormatRule);
  } else {
    // Use the national prefix formatting rule instead.
    String nationalPrefixFormattingRule =
        formattingPattern.nationalPrefixFormattingRule;
    if (numberFormat == PhoneNumberFormat.national &&
        nationalPrefixFormattingRule.isNotEmpty) {
      String format = numberFormatRule.replaceFirst(
          firstGroupPattern, nationalPrefixFormattingRule);
      formattedNationalNumber =
          replaceAllAndFormat(nationalNumber, patternToMatch, format);
    } else {
      formattedNationalNumber = replaceAllAndFormat(
          nationalNumber, patternToMatch, numberFormatRule);
    }
  }
  if (numberFormat == PhoneNumberFormat.rfc3966) {
    // Strip any leading punctuation.
    RegExp separatorPattern = RegExp(r'^' + _separatorPattern);
    if (separatorPattern.matchAsPrefix(formattedNationalNumber) != null) {
      formattedNationalNumber =
          replaceAllAndFormat(formattedNationalNumber, separatorPattern, '');
    }
    // Replace the rest with a dash between each number group.
    formattedNationalNumber = replaceAllAndFormat(
        formattedNationalNumber, RegExp(_separatorPattern), '-');
  }
  return formattedNationalNumber;
}