模式 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;
}