How to check if a String is numeric in Java

前端 未结 30 2638
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  一个人的身影
    2020-11-21 05:58

    Regex Matching

    Here is another example upgraded "CraigTP" regex matching with more validations.

    public static boolean isNumeric(String str)
    {
        return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
    }
    
    1. Only one negative sign - allowed and must be in beginning.
    2. After negative sign there must be digit.
    3. Only one decimal sign . allowed.
    4. After decimal sign there must be digit.

    Regex Test

    1                  --                   **VALID**
    1.                 --                   INVALID
    1..                --                   INVALID
    1.1                --                   **VALID**
    1.1.1              --                   INVALID
    
    -1                 --                   **VALID**
    --1                --                   INVALID
    -1.                --                   INVALID
    -1.1               --                   **VALID**
    -1.1.1             --                   INVALID
    

提交回复
热议问题