利用正则表达式判断是否为数字

来源:互联网 发布:淘宝自粘墙纸有甲醛吗 编辑:程序博客网 时间:2024/05/18 11:12
    public static void main(String[] args) {        String str = null;        boolean flag = isNumeric(str);        System.out.println(flag);        String str1 = "";        boolean flag1 = isNumeric(str1);        System.out.println(flag1);        String str2 = "中文";        boolean flag2 = isNumeric(str2);        System.out.println(flag2);        String str3 = "-1";        boolean flag3 = isNumeric(str3);        System.out.println(flag3);        String str4 = "9";        boolean flag4 = isNumeric(str4);        System.out.println(flag4);        String str5 = "1.1";        boolean flag5 = isNumeric(str5);        System.out.println(flag5);    }    /**     * 匹配是否包含数字     * @param str 可能为中文,也可能是-19162431.1254,不使用BigDecimal的话,变成-1.91624311254E7     * @return     * @author yutao     * @date 2016年11月14日下午7:41:22     */    public static boolean isNumeric(String str) {        // 该正则表达式可以匹配所有的数字 包括负数        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");        String bigStr;        try {            bigStr = new BigDecimal(str).toString();        } catch (Exception e) {            return false;//异常 说明包含非数字。        }        Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配        if (!isNum.matches()) {            return false;        }        return true;    }