我在找一个方法,该方法返回布尔如果串通过是一个有效的数量(例如"123.55e-9","-333,556").我 不不 只想做的事:

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

显然,功能应该使用国家机(外交部)分析串,以确保无效的例子不要欺骗(例如"-21,22.22.2", "33-2").你知道如果任何这样的文库的存在?我不真的想把它写我自己,因为它是这样一个明显的问题,我敢肯定我会被重新发明车轮。

谢谢,

尼克

有帮助吗?

解决方案

我将避免重新发明了这种方法,并与Apache共用。如果您使用弹簧的、支柱或其他许多常用java库,他们往往有Apache commons包括在内。你会想的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

其他提示

使用 regexp

确切的经常表达的指定Javadocs为 Double.valueOf(String).

为了避免调用此方法上的一串无效的并具有一个 NumberFormatException 被抛出,经常表达的以下可以使用屏幕输入string:

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
}

下面是一个基于正则表达式的效用函数工作正常(可能不适合的“”检查在正规表达式,同时保持它可读):

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

}

呀正则表达式应该做的伎俩。我只知道的.Net正则表达式,但所有的正则表达式语言是非常相似的,所以这应该让你开始。我没有测试它,所以你可能要踢它与周围的正则表达式的Java类了一下。

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

一些正则表达式语法控制的:结果 ? - 可选元素点击 | - OR操作。基本上我允许带或不带逗号的数字,如果他们被正确格式化。结果 [] - 设置允许的字符结果 {,} - 元件,点击的最小最大 * - 任意数目的元素,0到无穷大搜索 + - 的至少一种元素,1至无穷大,点击 \ - 转义符结果 。 - 任何字符(因此,为什么它被转义)结果

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top