一、引入依赖包
<!-- Google 官方全球手机号解析库(必加) -->
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>8.13.47</version>
</dependency>
二、工具类
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
/**
* @author Alan Chen
* @description 全球手机号码 - 自动提取国家/地区码(区号)
* @date 2026/4/16
*/
public class GlobalPhoneCodeUtil {
private static final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
public static String getGlobalCountryCode(String globalPhone) {
if (globalPhone == null || globalPhone.isBlank()) {
return null;
}
String original = globalPhone.trim();
try {
Phonenumber.PhoneNumber number;
// ============= 全球通用规则:最高优先级 =============
// 1. 以 + 开头 → 完全交给 Google 库自动识别(全球所有国家都正确)
if (original.startsWith("+")) {
number = phoneUtil.parse(original, null);
}
// 2. 带横杠 -(如 853-xxxx)→ 按澳门解析,自动提取区号
else if (original.contains("-")) {
number = phoneUtil.parse(original, "MO");
}
// 3. 11位纯数字 → 中国大陆 86
else if (original.replaceAll("[^0-9]", "").length() == 11) {
number = phoneUtil.parse(original, "CN");
}
// 4. 8位纯数字 → 澳门 853
else {
number = phoneUtil.parse(original, "MO");
}
return String.valueOf(number.getCountryCode());
} catch (NumberParseException e) {
return null;
}
}
// ====================== 测试 ======================
public static void main(String[] args) {
// 你原来的例子
System.out.println(getGlobalCountryCode("853-66202339")); // 853 ✅
System.out.println(getGlobalCountryCode("13802838734")); // 86 ✅
System.out.println(getGlobalCountryCode("66623689")); // 853 ✅(澳门)
// 全球测试
System.out.println(getGlobalCountryCode("+85291234567")); // 852 ✅(香港)
System.out.println(getGlobalCountryCode("+12125551234")); // 1 ✅(美国/加拿大)
System.out.println(getGlobalCountryCode("+60123456789")); // 60 ✅(马来西亚)
System.out.println(getGlobalCountryCode("+919876543210")); // 91 ✅(印度)
System.out.println(getGlobalCountryCode("+886912345678")); // 886 ✅(台湾)
System.out.println(getGlobalCountryCode("+6588888888")); // 65 ✅(新加坡)
System.out.println(getGlobalCountryCode("+447911123456")); // 44 ✅(英国)
System.out.println(getGlobalCountryCode("+61412345678")); // 61 ✅(澳大利亚)
}
}