Java判断字符串是否为数字

800 阅读1分钟
  1. 巧用正则
public static boolean isNumeric(String str){
    Pattern pattern = Pattern.compile("[0-9]*");
    if(str.indexOf(".")>0){//判断是否有小数点
        if(str.indexOf(".")==str.lastIndexOf(".") && str.split("\.").length==2){ //判断是否只有一个小数点
            return pattern.matcher(str.replace(".","")).matches();
        }else {
            return false;
        }
    }else {
        return pattern.matcher(str).matches();
    }
}
  1. 正则
public static boolean isNumeric(String str) {
    Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
    if (pattern.matcher(str).matches()) {
        return true;
    }
    return false;
}

由于数字和小数的情况较多,最终的正则需要不断的尝试和完善:

  • "-?[0-9]+.?[0-9]+" 点号.,是匹配任意字符,需要进行转义
  • "-?[0-9]+\.?[0-9]+" 小数的情况没考虑完全
  • "-?[0-9]+(\.[0-9]+)?" 最终结果
  • "-?[1-9][0-9]*(\.[0-9]+)?" 完善