如何在Java中将电话号码格式化为字符串?

我一直存储电话号码,我想在将电话号码打印成字符串时添加连字符。

我尝试使用DecimalFormat但不喜欢连字符。 可能是因为它用于格式化十进制数而不是长数。

 long phoneFmt = 123456789L; DecimalFormat phoneFmt = new DecimalFormat("###-###-####"); System.out.println(phoneFmt.format(phoneNum)); //doesn't work as I had hoped 

理想情况下,我也希望在区号上加上括号。

 new DecimalFormat("(###)-###-####"); 

这样做的正确方法是什么?

你可以使用String.replaceFirst和regex方法一样

  long phoneNum = 123456789L; System.out.println(String.valueOf(phoneNum).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)-$2-$3")); 

要获得所需的输出:

 long phoneFmt = 123456789L; //get a 12 digits String, filling with left '0' (on the prefix) DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000"); String phoneRawString= phoneDecimalFmt.format(phoneFmt); java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}"); //suposing a grouping of 3-3-4 String[] phoneNumArr={phoneRawString.substring(0, 3), phoneRawString.substring(3,6), phoneRawString.substring(6)}; System.out.println(phoneMsgFmt.format(phoneNumArr)); 

控制台的结果如下所示:

(012)-345-6789

要存储电话号码,您应该考虑使用数字以外的数据类型 。

最简单的方法是使用javax.swing.text库中内置的MaskFormatter。

你可以这样做:

 import javax.swing.text.MaskFormatter; String phoneMask= "###-###-####"; String phoneNumber= "123423452345"; MaskFormatter maskFormatter= new MaskFormatter(phoneMask); maskFormatter.setValueContainsLiteralCharacters(false); maskFormatter.valueToString(phoneNumber) ; 

如果你真的需要正确的方法,那么你可以使用Google最近开源的libphonenumber

最糟糕的解决方案是:

 StringBuilder sb = new StringBuilder(); long tmp = phoneFmt; sb.append("("); sb.append(tmp / 10000000); tmp = tmp % 10000000; sb.append(")-"); sb.apppend(tmp / 10000); tmp = tmp % 10000000; sb.append("-"); sb.append(tmp); 

这就是我最终做到的方式:

 private String printPhone(Long phoneNum) { StringBuilder sb = new StringBuilder(15); StringBuilder temp = new StringBuilder(phoneNum.toString()); while (temp.length() < 10) temp.insert(0, "0"); char[] chars = temp.toString().toCharArray(); sb.append("("); for (int i = 0; i < chars.length; i++) { if (i == 3) sb.append(") "); else if (i == 6) sb.append("-"); sb.append(chars[i]); } return sb.toString(); } 

我知道这不支持国际号码,但我不是在写一个“真正的”应用程序,所以我并不关心这一点。 我只接受10个字符长的电话号码。 我只是想用一些格式打印它。

谢谢你的回复。

你可以实现自己的方法为你做这件事,我建议你使用这样的东西。 使用DecimalFormatMessageFormat 。 使用此方法,您可以使用任何您想要的任何内容( String,Integer,Float,Double ),输出将始终正确。

 import java.text.DecimalFormat; import java.text.MessageFormat; /** * Created by Yamil Garcia Hernandez on 25/4/16. */ public class test { // Constants public static final DecimalFormat phoneFormatD = new DecimalFormat("0000000000"); public static final MessageFormat phoneFormatM = new MessageFormat("({0}) {1}-{2}"); // Example Method on a Main Class public static void main(String... args) { try { System.out.println(formatPhoneNumber("8091231234")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber("18091231234")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber("451231234")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber("11231234")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber("1231234")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber("231234")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber("")); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber(0)); } catch (Exception e) { e.printStackTrace(); } try { System.out.println(formatPhoneNumber(8091231234f)); } catch (Exception e) { e.printStackTrace(); } } // Magic public static String formatPhoneNumber(Object phone) throws Exception { double p = 0; if (phone instanceof String) p = Double.valueOf((String) phone); if (phone instanceof Integer) p = (Integer) phone; if (phone instanceof Float) p = (Float) phone; if (phone instanceof Double) p = (Double) phone; if (p == 0 || String.valueOf(p) == "" || String.valueOf(p).length() < 7) throw new Exception("Paramenter is no valid"); String fot = phoneFormatD.format(p); String extra = fot.length() > 10 ? fot.substring(0, fot.length() - 10) : ""; fot = fot.length() > 10 ? fot.substring(fot.length() - 10, fot.length()) : fot; String[] arr = { (fot.charAt(0) != '0') ? fot.substring(0, 3) : (fot.charAt(1) != '0') ? fot.substring(1, 3) : fot.substring(2, 3), fot.substring(3, 6), fot.substring(6) }; String r = phoneFormatM.format(arr); r = (r.contains("(0)")) ? r.replace("(0) ", "") : r; r = (extra != "") ? ("+" + extra + " " + r) : r; return (r); } } 

结果将是

 (809) 123-1234 +1 (809) 123-1234 (45) 123-1234 (1) 123-1234 123-1234 023-1234 java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842) at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.lang.Double.parseDouble(Double.java:538) at java.lang.Double.valueOf(Double.java:502) at test.formatPhoneNumber(test.java:66) at test.main(test.java:45) java.lang.Exception: Paramenter is no valid at test.formatPhoneNumber(test.java:78) at test.main(test.java:50) (809) 123-1232 

DecimalFormat不允许对数字中的任意文本进行格式化,就像前缀或后缀一样。 所以它无法帮助你。

在我看来,将电话号码存储为数字值是完全错误的。 如果我想存储国际号码怎么办? 许多国家/地区使用+来表示国家/地区代码(例如,美国/ Canda为+1 ),其他国家/地区使用00 (例如001 )。

这两个都无法真正用数字数据类型表示(“那个数字是1555123还是001555123?”)

您也可以使用https://github.com/googlei18n/libphonenumber 。 这是一个例子:

 import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; String s = "18005551234"; PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(s, Locale.US.getCountry()); String formatted = phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL); 

在这里,您可以在类路径上获取库: http : //mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber

U可以将包含非数字字符的任何字符串格式化为所需的格式,使用我的util类进行格式化

用法很简单

 public static void main(String[] args){ String num = "ab12345*&67890"; System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10)); } 

输出:(123)-456-7890

你可以指定任何foramt,如XXX-XXX-XXXX和电话号码的长度,如果输入长度大于指定的长度,那么将修剪字符串。

从这里获取我的课程: https : //github.com/gajeralalji/PhoneNumberUtil/blob/master/PhoneNumberUtil.java

我原以为你需要使用MessageFormat而不是DecimalFormat。 那应该更灵活。

您也可以使用子字符串和连接来轻松格式化。

 telephoneNumber = "("+telephoneNumber.substring(0, 3)+")-"+telephoneNumber.substring(3, 6)+"-"+telephoneNumber.substring(6, 10); 

但有一点需要注意的是,您必须检查电话号码字段的长度,以确保您的格式安全。

String formatterPhone = String.format(“%s-%s-%s”,phoneNumber.substring(0,3),phoneNumber.substring(3,6),phoneNumber.substring(6,10));

 Pattern phoneNumber = Pattern.compile("(\\d{3})(\\d{3})(\\d{4})"); // ... Matcher matcher = phoneNumber(numberAsLineOf10Symbols); if (matcher.matches) { return "(" + matcher.group(1) + ")-" +matcher.group(2) + "-" + matcher.group(3); }