-1

I am using libphonenumber-csharp and when I make the following call:

PhoneNumberUtil = PhoneNumberUtil.GetInstance();
var phoneNumber = PhoneNumberUtil.Parse(e164PhoneNumber, null);
return PhoneNumberUtil.Format(phoneNumber, PhoneNumberFormat.INTERNATIONAL);

I get "+1 303-123-4567". How can I instead get "+1 (303) 123-4567"?

Is my best bet to use regular expressions and if it's "+1 ###-###-####" then adjust it? I think that would be safe as the +1 tells me it's U.S.

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • The unit tests suggest you can make a [custom format](https://github.com/twcclegg/libphonenumber-csharp/blob/7f80fb67da38eb9578ff88b52433940f8fe5a43e/csharp/PhoneNumbers.Test/TestPhoneNumberUtil.cs#L846). It does not seem like a great idea, but you can. – teapot418 Aug 15 '23 at 17:05
  • The above seems a bit fragile and probably wrong for non-US numbers. Do you need it for non-US numbers as well? – teapot418 Aug 15 '23 at 17:08
  • @teapot418 I'd like number for any country to be formatted in the standard for that locale? The standard for the U.S. is "(303) 123-4567" not "303-123-4567". So any way to get the local standard? – David Thielen Aug 15 '23 at 17:21
  • 1
    I'm afraid the available libraries follow [E.123](https://www.itu.int/rec/T-REC-E.123-200102-I/en) and your desired format is a mix of the national and international format, which is unlikely to be directly supported. – teapot418 Aug 15 '23 at 17:30
  • Don't forget about extensions. We all have a 3-digit extension at work. – Dave S Aug 15 '23 at 18:27

1 Answers1

0

Here's what I did. It works. And it uses the libphonenumber returned string if it's not exactly "+1 303-123-4567..." and so should be safe. Keep in mind this does not need to handle all possible phone formats. It only needs to handle the format libphonenumber returns.

   private static PhoneNumberUtil? PhoneNumberUtil { get; }

   static MiscUtils()
    {
        PhoneNumberUtil = PhoneNumberUtil.GetInstance();
    }

   public static string FormatPhoneNumber(string e164PhoneNumber)
    {
        if (PhoneNumberUtil == null)
            return e164PhoneNumber;

        var phoneNumber = PhoneNumberUtil.Parse(e164PhoneNumber, null);
        var formattedNumber = PhoneNumberUtil.Format(phoneNumber, PhoneNumberFormat.INTERNATIONAL);
        // returns "+1 650-253-0000", maybe with an extension
        if (!PhoneRegex.IsMatch(formattedNumber))
            return formattedNumber;
        // Want "+1 (650) 253-0000"
        return $"+1 ({formattedNumber[3..6]}) {formattedNumber[7..]}";
    }
David Thielen
  • 28,723
  • 34
  • 119
  • 193