問題描述
如果傳遞的字符串是有效數字(例如123.55e-9"、-333,556"),我正在尋找一種返回布爾值的方法.我不想只想做:
I'm looking for a method that returns a boolean if the String it is passed is a valid number (e.g. "123.55e-9", "-333,556"). I don't want to just do:
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").你知道是否存在這樣的圖書館嗎?我真的不想自己寫它,因為這是一個顯而易見的問題,我敢肯定我會重新發明輪子.
Clearly, the function should use a state machine (DFA) to parse the string to make sure invalid examples don't fool it (e.g. "-21,22.22.2", "33-2"). Do you know if any such library exists? I don't really want to write it myself as it's such an obvious problem that I'm sure I'd be re-inventing the wheel.
謝謝,
尼克
推薦答案
我會避免重新發明這種方法并使用 Apache Commons.如果您使用 Spring、Struts 或許多其他常用的 java 庫,它們通常包含 Apache commons.您將需要 commons-lang.jar 文件.這是 NumberUtils 你想要的:
I would avoid re-inventing this method and go with Apache Commons. If your using Spring, Struts or many other commonly used java libraries, they often have Apache commons included. You will want the commons-lang.jar file. Here is the method in NumberUtils you would want:
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
這篇關于用于檢查字符串是否包含*無*異常的數字的 Java 庫的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!