문제

내가 찾는 방법을 반환하는 부울 경우에는 문자열을 전달되는 것은 유효한 숫자(예."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.을 사용하는 경우에는 봄,스트럿 또는 다른 많은 일반적으로 사용되는 자바 라이브러리,그들은 종종 아파치가 공용 포함됩니다.원할 것입 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 for Double.valueOf(String).

를 피하는 이 메소드를 호출에 잘못된 문자열과 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
}

여기에 regexp 기반으로 유틸리티 기능이 잘 작동하고(맞지 않을 수""확인에서 정규 표현식을 유지하면서 읽을 수 있는):

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 regexp 지 모든 정규식 언어는 상당히 비슷한다 그래서 당신은 시작합니다.지 않았을 테스트 할 수 있습니다,그래서 그것을 걷어차 주변에 조금 Java regex 클래스입니다.

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

의 일부 Regex 제어 syntax:
?-선택적 요소
|또는 연산자입니다.기본적으로 허용된 숫자와 함께 또는없이 쉼표로 구분하는 경우 그들은 형식이 잘못되었습니다..
[]-Set 허용되는 캐릭터
{,}-최소한의 최고의 요소
**모든 요소의 개수,0~무한대
+-적어도 하나의 요소 1 인피니티
\탈출 캐릭터
.-모든 문자(따라서 왜 그것을 탈출했)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top