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


当前回答

您可以使用Apache Commons Lang中的NumberUtils.isCreatable()。

因为NumberUtils。isNumber将在4.0中被弃用,所以使用NumberUtils.isCreatable()代替。

其他回答

解析它(即使用Integer#parseInt)并简单地捕获异常。=)

澄清一下:parseInt函数检查它是否可以在任何情况下解析该数字(显然),如果您想无论如何都要解析它,那么实际进行解析不会对性能造成任何影响。

如果您不想解析它(或者很少解析它),当然您可能希望采用不同的方法。

如果字符串可能包含小数,则可以使用BigDecimal:

try {
    new java.math.BigInteger(testString);
} catch(NumberFormatException e) {
    throw new RuntimeException("Not a valid number");
}

异常开销很大,但在这种情况下,RegEx需要更长的时间。下面的代码显示了两个函数的简单测试——一个使用异常,一个使用正则表达式。在我的机器上,RegEx版本比异常慢10倍。

import java.util.Date;


public class IsNumeric {

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

public static boolean isNumericTwo(String s) {
    try {
        Double.parseDouble(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static void main(String [] args) {

    String test = "12345.F";

    long before = new Date().getTime();     
    for(int x=0;x<1000000;++x) {
        //isNumericTwo(test);
        isNumericOne(test);
    }
    long after = new Date().getTime();

    System.out.println(after-before);

}

}

如果你在android上,那么你应该使用:

android.text.TextUtils.isDigitsOnly(CharSequence str)

文档可以在这里找到

保持简单。大多数人都可以“重新编程”(同样的事情)。

我已经说明了一些不使用任何API检查数字和小数的条件,

检查固定长度1位数字

Character.isDigit(char)

检查固定长度编号(假设长度为6)

String number = "132452";
if(number.matches("([0-9]{6})"))
System.out.println("6 digits number identified");

检查变化长度之间的数量(假设4到6个长度)

//  {n,m}  n <= length <= m
String number = "132452";
if(number.matches("([0-9]{4,6})"))
System.out.println("Number Identified between 4 to 6 length");

String number = "132";
if(!number.matches("([0-9]{4,6})"))
System.out.println("Number not in length range or different format");

检查变长十进制数之间(假设长度为4到7)

//  It will not count the '.' (Period) in length
String decimal = "132.45";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1.12";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1234";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "-10.123";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "123..4";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "132";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "1.1";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

希望它能帮助到很多人。