Java:将字符串格式化为电话号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7730006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Format a string as a telephone number
提问by Justin Kredible
I have an unformatted telephone number string ("5551234567"). I would like to format this string for display purposes in the ui. The number should look like this after format:
我有一个未格式化的电话号码字符串(“5551234567”)。我想格式化这个字符串以在 ui 中显示。格式化后的数字应如下所示:
(555) 123-4567
(555) 123-4567
Sigh.....
叹.....
I was trying to find a generic way that would take into account both US and international phone numbers. I came accross the MaskFormatter in the JDK but discovered that there is a bug in the Javadoc. Which lead me to asking my question here. I was hoping for a solution where I could input a mask then the actual string. The output would be formatted accordingly for international/US numbers or if the wrong number of characters were specified, some default character would be displayed in place of the missing characters........
我试图找到一种通用方法,可以同时考虑美国和国际电话号码。我遇到了 JDK 中的 MaskFormatter,但发现 Javadoc 中有一个错误。这导致我在这里问我的问题。我希望有一个解决方案,我可以输入一个掩码,然后输入实际的字符串。输出将根据国际/美国号码进行相应的格式化,或者如果指定了错误的字符数,则会显示一些默认字符来代替丢失的字符......
回答by John B
String.format("(%s) %s-%s", number.substring(0, 3), number.substring(3, 6),
number.substring(6, 10));
回答by dlamblin
Is this homework? I'll leave it as an exercise to John to covert from Perl to Java. Should be simple; especially with something like http://www.regexbuddy.com/.
这是作业吗?我将把它作为练习留给 John,以便从 Perl 转换到 Java。应该很简单;尤其是像http://www.regexbuddy.com/这样的东西。
:~$ perl -pe 's/\D//g;s/^(\d{3})(\d{3})(\d{0,4})(\d*)/() -/'
5551234567
(555) 123-4567