Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

format - Java library to check whether a String contains a number *without* exceptions

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

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.

Thanks,

Nick

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...