正则表达式获取字符串中电话号码的方式

发布时间 2023-04-21 13:48:26作者: 伊芙宁西普

我一开始是想找数字1 然后切出11位数字这样
但是newbing给了一个简单了当的方法 正则表达式直接切11位数字
分享出来以供参考

     /**
     * @Description: 正则表达式寻找字符串中的电话号码
     * @param string 有11位电话存在的字段
     * @author: @NewBing
     * */
    public static String getPhoneNum(String string) {
        Pattern pattern = Pattern.compile("\\d{11}");
        Matcher matcher = pattern.matcher(string);
        if (matcher.find()) {
            return  matcher.group();
        }
        throw new HaiBangTuiException(ResponseCode.NOT_ACCEPTABLE,"无法找到"+string+"中的电话号码字段");
    }