简体   繁体   English

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

[英]How do format a phone number as a String in Java?

I have been storing phone numbers as longs and I would like to simply add hyphens when printing the phone number as a string.我一直将电话号码存储为 long,我想在将电话号码打印为字符串时简单地添加连字符。

I tried using DecimalFormat but that doesn't like the hyphen.我尝试使用DecimalFormat但它不喜欢连字符。 Probably because it is meant for formatting decimal numbers and not longs.可能是因为它用于格式化十进制数而不是长整数。

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

Ideally, I would like to have parenthesis on the area code too.理想情况下,我也希望在区号上加上括号。

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

What is the correct way to do this?这样做的正确方法是什么?

You can use String.replaceFirst with regex method like您可以将String.replaceFirst与正则表达式方法一起使用,例如

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

To get your desired output:要获得所需的输出:

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));

The result at the Console looks like this:控制台上的结果如下所示:

(012)-345-6789 (012)-345-6789

For storing phone numbers, you should consider using a data type other than numbers .为了存储电话号码,您应该考虑使用除 numbers 之外的数据类型

The easiest way to do this is by using the built in MaskFormatter in the javax.swing.text library .最简单的方法是使用javax.swing.text 库中的内置 MaskFormatter。

You can do something like this :你可以这样做:

import javax.swing.text.MaskFormatter;

String phoneMask= "###-###-####";
String phoneNumber= "123423452345";

MaskFormatter maskFormatter= new MaskFormatter(phoneMask);
maskFormatter.setValueContainsLiteralCharacters(false);
maskFormatter.valueToString(phoneNumber) ;

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

You could also use https://github.com/googlei18n/libphonenumber .您也可以使用https://github.com/googlei18n/libphonenumber Here is an example:下面是一个例子:

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);

Here you can get the library on your classpath: http://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber您可以在此处获取类路径中的库: http : //mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber

The worst possible solution would be:最糟糕的解决方案是:

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);

This is how I ended up doing it:这就是我最终这样做的方式:

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();
}

I understand that this does not support international numbers, but I'm not writing a "real" application so I'm not concerned about that.我知道这不支持国际号码,但我不是在编写“真正的”应用程序,所以我并不担心。 I only accept a 10 character long as a phone number.我只接受 10 个字符长的电话号码。 I just wanted to print it with some formatting.我只是想用一些格式打印它。

Thanks for the responses.感谢您的回复。

You can implement your own method to do that for you, I recommend you to use something such as this.您可以实现自己的方法来为您做到这一点,我建议您使用诸如此类的方法。 Using DecimalFormat and MessageFormat .使用DecimalFormatMessageFormat With this method you can use pretty much whatever you want ( String,Integer,Float,Double ) and the output will be always right.使用这种方法,您几乎可以使用任何您想要的东西( 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);
    }
}

Result will be结果将是

(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

U can format any string containing non numeric characters also to your desired format use my util class to format你可以将包含非数字字符的任何字符串格式化为你想要的格式,使用我的 util 类来格式化

usage is very simple用法很简单

public static void main(String[] args){
    String num = "ab12345*&67890";

    System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10));
}

output: (123)-456-7890输出:(123)-456-7890

u can specify any foramt such as XXX-XXX-XXXX and length of the phone number , if input length is greater than specified length then string will be trimmed.您可以指定任何格式,例如 XXX-XXX-XXXX 和电话号码的长度,如果输入的长度大于指定的长度,则字符串将被修剪。

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

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);
}

DecimalFormat doesn't allow arbitrary text within the number to be formatted, just as a prefix or a suffix. DecimalFormat不允许的数量之内任意文本进行格式化,只是作为前缀或后缀。 So it won't be able to help you there.所以它无法在那里帮助你。

In my opinion, storing a phone number as a numeric value is wrong, entirely.在我看来,将电话号码存储为数值完全是错误的。 What if I want to store an international number?如果我想存储一个国际号码怎么办? Many countries use + to indicate a country code (eg +1 for USA/Canda), others use 00 (eg 001 ).许多国家/地区使用+表示国家/地区代码(例如, +1表示美国/加拿大),其他国家/地区使用00 (例如001 )。

Both of those can't really be represented in a numeric data type ("Is that number 1555123 or 001555123?")这两者都不能真正用数字数据类型表示(“那个数字是 1555123 还是 001555123?”)

You could use the substring and concatenation for easy formatting too.您也可以使用子字符串和连接来轻松格式化。

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

But one thing to note is that you must check for the lenght of the telephone number field just to make sure that your formatting is safe.但需要注意的一件事是,您必须检查电话号码字段的长度,以确保您的格式是安全的。

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

I'd have thought you need to use a MessageFormat rather than DecimalFormat.我原以为您需要使用 MessageFormat 而不是 DecimalFormat。 That should be more flexible.那应该更灵活。

Using StringBuilder for performance.使用StringBuilder提高性能。

long number = 12345678L;

System.out.println(getPhoneFormat(String.valueOf(number)));

public static String getPhoneFormat(String number)
{
    if (number == null || number.isEmpty() || number.length() < 6 || number.length() > 15)
    {
        return number;
    }

    return new StringBuilder("(").append(number.substring(0, 3))
            .append(") ").append(number.substring(3, 6))
            .append("-").append(number.substring(6))
            .toString();

}

Kotlin科特林

val number = 088899998888

val phone = number.phoneFormatter()

fun String.phoneFormatter(): String { return this.replace("\\B(?=(\\d{4})+(?!\\d))".toRegex(), "-") }

The result will be 0888-9999-8888结果将是0888-9999-8888

I used this one我用过这个

String columValue = "1234567890字符串 columValue = "1234567890

String number = columValue.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3"); String number = columValue.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM