模式 1(786) 1234 5678

給定標準化的電話號碼,如+178612345678,我們將獲得帶有提供的模式的格式化數字。

private String getFormattedNumber(String phoneNumber) {
    
    PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    
    Phonemetadata.NumberFormat numberFormat = new Phonemetadata.NumberFormat();
    
    numberFormat.pattern = "(\\d{3})(\\d{3})(\\d{4})";
    
    numberFormat.format = "($1) $2-$3";
    
    List<Phonemetadata.NumberFormat> newNumberFormats = new ArrayList<>();
    
    newNumberFormats.add(numberFormat);
    
    Phonenumber.PhoneNumber phoneNumberPN = null;
    
    try {
        phoneNumberPN = phoneNumberUtil.parse(phoneNumber, Locale.US.getCountry());
        phoneNumber = phoneNumberUtil.formatByPattern(phoneNumberPN, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL, newNumberFormats);
        
    } catch (NumberParseException e) {
        e.printStackTrace();
    }
    
    return phoneNumber;
}