我一直将电话号码存储为长整型,我想在将电话号码打印为字符串时简单地添加连字符。
我尝试使用
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 与正则表达式方法一起使用,例如
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
您还可以使用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
最糟糕的解决方案是:
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 个字符长的电话号码。我只是想用一些格式打印它。
感谢您的回复。
您可以实现自己的方法来为您做到这一点,我建议您使用类似的方法。使用
DecimalFormat
和 MessageFormat
。通过这种方法,您几乎可以使用任何您想要的东西 (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
不允许在要格式化的数字中内使用任意文本,就像前缀或后缀一样。所以它无法帮助你。
在我看来,将电话号码存储为数值是完全错误的。如果我想存储国际号码怎么办?许多国家/地区使用
+
来表示国家/地区代码(例如 +1
表示美国/加拿大),其他国家/地区则使用 00
(例如 001
)。
这两者都不能真正用数字数据类型表示(“这个数字是 1555123 还是 001555123?”)
您也可以使用子字符串和连接来轻松格式化。
telephoneNumber = "("+telephoneNumber.substring(0, 3)+")-"+telephoneNumber.substring(3, 6)+"-"+telephoneNumber.substring(6, 10);
但需要注意的一件事是,您必须检查电话号码字段的长度,以确保格式安全。
您可以将任何包含非数字字符的字符串格式化为您想要的格式,使用我的 util 类进行格式化
public static void main(String[] args){
String num = "ab12345*&67890";
System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10));
}
u 可以指定任何格式,如 XXX-XXX-XXXX 和电话号码的长度,如果输入长度大于指定长度,则字符串将被修剪。
从这里获取我的课程: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);
}
我认为您需要使用 MessageFormat 而不是 DecimalFormat。这样应该更灵活。
字符串格式化程序Phone = String.format("%s-%s-%s", 电话号码.substring(0, 3), 电话号码.substring(3, 6), 电话号码.substring(6, 10));
使用
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();
}
科特林
val number = 088899998888
val phone = number.phoneFormatter()
fun String.phoneFormatter(): String { return this.replace("\\B(?=(\\d{4})+(?!\\d))".toRegex(), "-") }
结果将是
0888-9999-8888
我用的是这个
字符串列值=“1234567890
字符串数字 = columValue.replaceFirst("(\d{3})(\d{3})(\d+)", "($1) $2-$3");
我使用以下代码
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Produces a string suitable for representing phone numbers by formatting them according with the format string
*/
@Slf4j
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder(builderMethodName = "builderInternal")
public class PhoneNumberFormatter {
/** Format string used to represent phone numbers */
@Getter @Builder.Default private String formatString = "(###)###-";
/** String used to represent null phone numbers */
@Getter @Builder.Default private String nullString = "---";
/** Pattern used for substitutions of phone numbers.
* Pounds (#) are replaced by phone digits unless they are escaped (\#) */
private static final Pattern PATTERN = Pattern.compile("\\\\#|#");
/** Returns a new formatter with default parameters */
public static PhoneNumberFormatter of() {
return builder().build();
}
/** Returns a new formatter with the format string */
public static PhoneNumberFormatter of(String formatString) {
return builder(formatString).build();
}
/** Create a builder object. Notice that lombok does most of the work in builderInternal
* but we want to pass the format string to the builder method directly */
public static PhoneNumberFormatterBuilder builder(String formatString) {
Objects.requireNonNull(formatString, "formatString");
return builder().formatString(formatString);
}
/** Create a new builder with default parameters. Notice that builderInternal is created by lombok */
public static PhoneNumberFormatterBuilder builder() {
return builderInternal();
}
/** Return a formatted string corresponding to the given user */
public String format(String phoneNumber) {
StringBuilder buf = new StringBuilder(32);
formatTo(phoneNumber, buf);
return buf.toString();
}
/** Append a formatted string corresponding to the given user to the given appendable */
public void formatTo(String phoneNumber, Appendable appendable) {
Objects.requireNonNull(appendable, "appendable");
if (appendable instanceof StringBuilder) {
doFormat(phoneNumber, (StringBuilder) appendable);
} else {
// buffer output to avoid writing to appendable in case of error
StringBuilder buf = new StringBuilder(32);
doFormat(phoneNumber, buf);
try {
appendable.append(buf);
} catch (IOException e) {
log.warn("Could not append phone number {} to {appendable}", phoneNumber, e);
}
}
}
/** Performs regex search and replacement of digits */
private void doFormat(String phoneNumber, StringBuilder result) {
if (phoneNumber == null) {
result.append(nullString);
return;
}
Matcher matcher = PATTERN.matcher(formatString);
int digitIndex = 0;
while (matcher.find()) {
if (matcher.group().equals("\\#")) {
matcher.appendReplacement(result, "#");
} else if (digitIndex < phoneNumber.length()) {
matcher.appendReplacement(result, String.valueOf(phoneNumber.charAt(digitIndex)));
digitIndex++;
} else {
break; // Stop if there are no more digits in the phone number
}
}
matcher.appendTail(result);
result.append(phoneNumber.substring(digitIndex));
}
}