pom:
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>8.12.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.136</version>
</dependency>
测试代码:
public static void main(String[] args) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber ph = null;
try {
// String mobile = "8615700498575";
String mobile = "8615700498575";
if(mobile.contains("+")){
System.out.println("1: "+mobile);
}else {
System.out.println(mobile);
StringBuilder stringBuilder = new StringBuilder("+");
stringBuilder.append(mobile);
mobile = stringBuilder.toString();
System.out.println("2: "+mobile);
}
ph = phoneUtil.parse(mobile,null);
String dialCode = String.valueOf(ph.getCountryCode());
String phone = String.valueOf(ph.getNationalNumber());
System.out.println("dialCode:{}"+dialCode);
System.out.println("phone:{}"+phone);
} catch (NumberParseException e) {
e.printStackTrace();
}
}
结果:
自己写的工具类:
package com.ppmath.mathcore.tool;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.ppmath.mathcore.controller.UserController;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PhoneUtil {
private static Logger log = LoggerFactory.getLogger(PhoneUtil.class);
/**得到手机号和区号*/
public static ArePhone getAreAndPhone(String username){
if(username == null){
return null;
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber ph = null;
String dialCode = null;
String phone = null;
ArePhone arePhone = new ArePhone();
try {
String mobile = username;
if(mobile.contains("+")){
}else {
System.out.println(mobile);
StringBuilder stringBuilder = new StringBuilder("+");
stringBuilder.append(mobile);
mobile = stringBuilder.toString();
}
ph = phoneUtil.parse(mobile,null);
dialCode = String.valueOf(ph.getCountryCode());
phone = String.valueOf(ph.getNationalNumber());
arePhone.setAreCode(dialCode)
.setPhone(phone);
} catch (NumberParseException e) {
log.warn("不是手机号");
arePhone = null;
}
return arePhone;
}
/**判断是否是手机号*/
public static Boolean judgeAreAndPhone(String username){
ArePhone arePhone = getAreAndPhone(username);
if(arePhone == null){
return false;
}else {
return true;
}
}
/**得到带加号的账号名*/
public static String getAddPhoneUsername(String username){
String oldUsername = username;
if(judgeAreAndPhone(username)){
StringBuilder stringBuilder = new StringBuilder("+");
stringBuilder.append(username);
return stringBuilder.toString();
}else {
return oldUsername;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public static class ArePhone{
private String areCode;
private String phone;
}
}