美文网首页
手机号区号和特殊符号处理神器

手机号区号和特殊符号处理神器

作者: 蓉漂里的小白 | 来源:发表于2021-07-31 14:22 被阅读0次

在做项目的时候经常会遇到手机号格式问题,有的人格式xxx/xxx-xxx; 有的是(xxx)-xxxxx 有的是xxx-xxxx
甚至有的公司有海外用户区号更是一大堆后端处理起来让人极其头疼。
今天就介绍一款手机号区号和特殊符号格式化的利器,可以帮助我们减轻工作量,
同时这个利器还支持国外手机号的格式化和识别能力。但是有一个前提条件就是必须要带上区号,支持设置默认区号(如果用户不传区号就添加默认区号)

神器 PhoneNumberUtil

这是一款由google 提供的手机号处理神器
1: 进入mvnrepository, 查找libphonenumber


image.png

2: 引入到我们的项目中

    <dependency>
        <groupId>com.googlecode.libphonenumber</groupId>
        <artifactId>libphonenumber</artifactId>
        <version>8.12.24</version>
    </dependency>
</dependencies>

3: 使用起来就非常简单了

public static String checkMobile(String phone) {
    if (StringUtils.isNotBlank(phone)) {
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber swissNumberProto = phoneUtil.parse(phone, "CN");
            return phoneUtil.format(swissNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
        } catch (NumberParseException e) {
            return "手机号不合法" + phone; 
        }
    }

    return phone;
}

4: 看测试效果:

System.out.println(checkMobile("+1 5159929344"));
System.out.println(checkMobile("(+1)5159929365"));
System.out.println(checkMobile("182/0098-6657"));
System.out.println(checkMobile("+86 183-8876 9987"));
image.png

相关文章

网友评论

      本文标题:手机号区号和特殊符号处理神器

      本文链接:https://www.haomeiwen.com/subject/yetkvltx.html