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


当前回答

String text="hello 123";
if(Pattern.matches([0-9]+))==true
System.out.println("String"+text);

其他回答

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

对于非负数用这个

public boolean isNonNegativeNumber(String str) {
  return str.matches("\\d+");
}

对于任何数字都使用这个

public boolean isNumber(String str) {
  return str.matches("-?\\d+");
}

//请检查下面的代码

public static boolean isDigitsOnly(CharSequence str) {
    final int len = str.length();
    for (int i = 0; i < len; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            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();
}
private static Pattern p = Pattern.compile("^[0-9]*$");

public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    return p.matcher(strNum).find();
}