java判断字符串是否为数字或小数

1.判断是否是数字

  public static boolean isNumericInt(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
  }


2.判断字符串是否为整数或者小数 方法一

public static boolean isNumeric(String str){
 
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


判断字符串是否为整数或者小数 方法二

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();
    }
}


3.java 判断一个字符串是不是整数、浮点数、科学计数(正则表达式)

public static boolean isNumeric(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        String regx = "[+-]*\\d+\\.?\\d*[Ee]*[+-]*\\d+";
        Pattern pattern = Pattern.compile(regx);
        boolean isNumber = pattern.matcher(str).matches();
        if (isNumber) {
            return isNumber;
        }
        regx = "^[-\\+]?[.\\d]*$";
        pattern = Pattern.compile(regx);
        return pattern.matcher(str).matches();
    }


如果以上方法返回的值为true,则可以进行下一步操作,比如将字符串转化为整数: Integer.parseInt(str),或者将字符串转化为小数: Double.valueOf(str)。
 

你可能感兴趣的:(小工具,JAVA,java,开发语言)