簡體   English   中英

用於檢查String是否包含數字*而沒有*異常的Java庫

[英]Java library to check whether a String contains a number *without* exceptions

我正在尋找一個方法,如果傳遞的字符串是有效數字(例如“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”)。 你知道這個庫是否存在嗎? 我真的不想自己寫,因為這是一個明顯的問題,我相信我會重新發明輪子。

謝謝,

缺口

我會避免重新發明這種方法並使用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

使用正則表達式

精確的正則表達式在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 } 

是的正則表達應該做的伎倆。 我只知道.Net regexp但所有正則表達式語言都非常相似,所以這應該讓你開始。 我沒有測試它,所以你可能想用Java regex類來解決它。

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

一些Regex控制語法:
- 可選元素
| - OR運算符。 基本上,如果數字格式正確,我允許使用或不使用逗號。
[] - 允許的字符集
{,} - 元素的最小值
* - 任意數量的元素,0到無窮大
+ - 至少一個元素,1到無窮大
\\ - 逃避角色
- 任何角色(因此它被逃脫的原因)

這是一個基於正則表達式的實用程序函數正常工作(無法在正則表達式中檢查“”檢查,同時保持其可讀性):

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM