在解析字符串之前,如何检查它是否是一个数字?


当前回答

我们可以尝试用("")即空格替换给定字符串中的所有数字,如果在此之后字符串的长度为零,那么我们可以说给定字符串只包含数字。 例子:

boolean isNumber(String str){
        if(str.length() == 0)
            return false; //To check if string is empty
        
        if(str.charAt(0) == '-')
            str = str.replaceFirst("-","");// for handling -ve numbers
    
        System.out.println(str);
        
        str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points
        
        if(str.length() == 0)
            return false; // to check if it is empty string after removing -ve sign and decimal point
        System.out.println(str);
        
        return str.replaceAll("[0-9]","").length() == 0;
    }

其他回答

要匹配仅包含ASCII数字的以10为基数的正整数,请使用:

public static boolean isNumeric(String maybeNumeric) {
    return maybeNumeric != null && maybeNumeric.matches("[0-9]+");
}

我认为唯一可靠地判断字符串是否是数字的方法是解析它。所以我只是解析它,如果它是一个数字,你可以免费得到整数形式的数字!

Java 8流,lambda表达式,函数接口

处理的所有情况(字符串空,字符串空等)

String someString = null; // something="", something="123abc", something="123123"

boolean isNumeric = Stream.of(someString)
            .filter(s -> s != null && !s.isEmpty())
            .filter(Pattern.compile("\\D").asPredicate().negate())
            .mapToLong(Long::valueOf)
            .boxed()
            .findAny()
            .isPresent();

下面是用于检查字符串是否为数字的类。它还修复数值字符串:

特点:

删除不必要的零["12.0000000" -> "12"] 删除不必要的零["12.0580000" -> "12.058"] 删除非数字字符["12.00sdfsdf00" -> "12"] 处理负字符串值["-12,020000" -> "-12.02"] 删除多个点["-12.0.20.000" -> "-12.02"] 没有额外的库,只有标准Java

给你…

public class NumUtils {
    /**
     * Transforms a string to an integer. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToInteger(String str) {
        String s = str;
        double d;
        d = Double.parseDouble(makeToDouble(s));
        int i = (int) (d + 0.5D);
        String retStr = String.valueOf(i);
        System.out.printf(retStr + "   ");
        return retStr;
    }

    /**
     * Transforms a string to an double. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToDouble(String str) {

        Boolean dotWasFound = false;
        String orgStr = str;
        String retStr;
        int firstDotPos = 0;
        Boolean negative = false;

        //check if str is null
        if(str.length()==0){
            str="0";
        }

        //check if first sign is "-"
        if (str.charAt(0) == '-') {
            negative = true;
        }

        //check if str containg any number or else set the string to '0'
        if (!str.matches(".*\\d+.*")) {
            str = "0";
        }

        //Replace ',' with '.'  (for some european users who use the ',' as decimal separator)
        str = str.replaceAll(",", ".");
        str = str.replaceAll("[^\\d.]", "");

        //Removes the any second dots
        for (int i_char = 0; i_char < str.length(); i_char++) {
            if (str.charAt(i_char) == '.') {
                dotWasFound = true;
                firstDotPos = i_char;
                break;
            }
        }
        if (dotWasFound) {
            String befDot = str.substring(0, firstDotPos + 1);
            String aftDot = str.substring(firstDotPos + 1, str.length());
            aftDot = aftDot.replaceAll("\\.", "");
            str = befDot + aftDot;
        }

        //Removes zeros from the begining
        double uglyMethod = Double.parseDouble(str);
        str = String.valueOf(uglyMethod);

        //Removes the .0
        str = str.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");

        retStr = str;

        if (negative) {
            retStr = "-"+retStr;
        }

        return retStr;

    }

    static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

}

这通常是通过一个简单的用户定义函数来完成的(例如,roll your-own的“isNumeric”函数)。

喜欢的东西:

public static boolean isNumeric(String str) { 
  try {  
    Double.parseDouble(str);  
    return true;
  } catch(NumberFormatException e){  
    return false;  
  }  
}

然而,如果您经常调用这个函数,并且由于不是一个数字,您希望许多检查失败,那么这种机制的性能就不会很好,因为您依赖于每次失败都会抛出异常,这是一个相当昂贵的操作。

另一种方法可能是使用正则表达式来检查是否是一个数字:

public static boolean isNumeric(String str) {
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

但是要小心上面的RegEx机制,因为如果你使用非阿拉伯数字(即0到9以外的数字),它会失败。这是因为RegEx的“\d”部分只匹配[0-9],并且有效地不具有国际数字意识。(感谢OregonGhost指出这一点!)

甚至另一种替代方法是使用Java内置的Java .text. numberformat对象来查看解析字符串后解析器的位置是否位于字符串的末尾。如果是,我们可以假设整个字符串都是数字:

public static boolean isNumeric(String str) {
  ParsePosition pos = new ParsePosition(0);
  NumberFormat.getInstance().parse(str, pos);
  return str.length() == pos.getIndex();
}