用于检查String是否包含数字*而没有*异常的Java库

时间:2009-07-22 07:27:40

标签: java format numbers bigdecimal state-machine

我正在寻找一种方法,如果传递的字符串是有效数字(例如“123.55e-9”,“ - 333,556”),则返回布尔值。我想要这样做:

public boolean isANumber(String s) {
    try { 
        BigDecimal a = new BigDecimal(s); 
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

显然,该函数应使用状态机(DFA)来解析字符串,以确保无效示例不会欺骗它(例如“-21,22.22.2”,“33-2”)。你知道这个库是否存在吗?我真的不想自己写,因为这是一个明显的问题,我确信我会重新发明轮子。

谢谢,

尼克

5 个答案:

答案 0 :(得分:6)

我会避免重新发明这种方法并使用Apache Commons。如果你使用Spring,Struts或许多其他常用的java库,它们通常都包含Apache公共。你会想要commons-lang.jar文件。以下是NumberUtils中您想要的方法:

isNumber[1]

public static boolean isNumber(java.lang.String str)
Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).

Null and empty String will return false.

Parameters:
str - the String to check
Returns:
true if the string is a correctly formatted number

答案 1 :(得分:3)

使用regexp

答案 2 :(得分:3)

Double.valueOf(String)的Javadocs中指定了精确的正则表达式。

  

为避免在无效字符串上调用此方法并抛出NumberFormatException,可以使用下面的正则表达式来筛选输入字符串:

final String Digits     = "(\\p{Digit}+)";
final String HexDigits  = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally 
// signed decimal integer.
final String Exp        = "[eE][+-]?"+Digits;
final String fpRegex    =
       ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
        "[+-]?(" + // Optional sign character
        "NaN|" +           // "NaN" string
        "Infinity|" +      // "Infinity" string

        // A decimal floating-point string representing a finite positive
        // number without a leading sign has at most five basic pieces:
        // Digits . Digits ExponentPart FloatTypeSuffix
        // 
        // Since this method allows integer-only strings as input
        // in addition to strings of floating-point literals, the
        // two sub-patterns below are simplifications of the grammar
        // productions from the Java Language Specification, 2nd 
        // edition, section 3.10.2.

        // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
        "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+

        // . Digits ExponentPart_opt FloatTypeSuffix_opt
        "(\\.("+Digits+")("+Exp+")?)|"+

        // Hexadecimal strings
        "((" +
        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
        "(0[xX]" + HexDigits + "(\\.)?)|" +

        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +

        ")[pP][+-]?" + Digits + "))" +
        "[fFdD]?))" +
        "[\\x00-\\x20]*"); // Optional trailing "whitespace"

if (Pattern.matches(fpRegex, myString))
    Double.valueOf(myString); // Will not throw NumberFormatException
else {
    // Perform suitable alternative action
}

答案 3 :(得分:2)

是的,正则表达式应该可以解决问题。我只知道.Net regexp但所有正则表达式语言都非常相似,所以这应该让你开始。我没有测试它,所以你可能想用Java正则表达式来解决它。

"-?(([0-9]{1,3}(,[0-9{3,3})*)|[0-9]*)(\.[0-9]+(e-?[0-9]*)?)?"

一些正则表达式控制语法:
? - 可选元件
| - OR运算符。基本上,如果格式正确,我允许带或不带逗号的数字 [] - 允许的字符集 {,} - 元素的最小最大值
* - 任意数量的元素,0到无穷大
+ - 至少一个元素,1到无穷大
\ - 逃脱角色
。 - 任何角色(因此它被逃脱的原因)

答案 4 :(得分:2)

这是一个基于正则表达式的实用程序函数正常工作(无法在正则表达式中检查“”,同时保持其可读性):

public class TestRegexp {
    static final String NUM_REGEX=
        "-?((([0-9]{1,3})(,[0-9]{3})*)|[0-9]*)(\\.[0-9]+)?([Ee][0-9]*)?";
    public static boolean isNum(String s) {
            return s!=null && s.length()>0 && s.matches(NUM_REGEX);  
    }
    public static void main(String[]args) {
        String[] values={
                "",
                "0",
                "0.1",
                ".1",
                "-.5E5",
                "-12,524.5E5",
                "-452,456,456,466.5E5",
                "-452,456,456,466E5",
                "22,22,2.14123415e1",
        };
        for (String value : values) {
            System.out.println(value+" is a number: "
            +isNum(value));
        }
    }

}