java 判斷一個字符串是否是數字

一、用 java 自帶的函數

    /**
     * 判斷一個 string 類型的字符串是不是一個數字
     *
     * @param str string 類型的字符串
     * @return <code>true</code> 該 string 類型的字符串是十進制正整數. 其他的會返回<code>false</code>
     */
    private static boolean judgeByToCharArray(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }
        return str.chars().allMatch(Character::isDigit);
    }

二、使用正則表達式

    /**
     * 使用正則表達式判斷字符串是否是數字
     *
     * @param str string 類型的字符串
     * @return <code>true</code> 該 string 是整數. 其他的會返回<code>false</code>
     */
    public static boolean isNumericByRegEx(String str) {
        // ?:0或1個, *:0或多個, +:1或多個 
        // 匹配所有整數
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        // 匹配小數
        Pattern pattern2 = Pattern.compile("^[-\\+]?[\\d]+[.][\\d]+$");
        return pattern.matcher(str).matches() || pattern2.matcher(str).matches();
    }

三、使用 ascii 碼

    /**
     * 使用 ASCII 碼判斷字符串是否是數字
     *
     * @param str string 類型的字符串
     * @return <code>true</code> 該 string 類型的字符串是十進制正整數. 其他的會返回<code>false</code>
     */
    public static boolean isNumericByAscii(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return str.chars().allMatch(chr -> (chr >= 48 && chr <= 57));
    }

四、parse 方法

    /**
     * 判斷一個 string 類型的字符串是不是一個數字
     *
     * @param str string 類型的字符串
     * @return <code>true</code> 該 string 類型的字符串是十進制正整數. 其他的會返回<code>false</code>
     */
    public static boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            try {
                Double.parseDouble(str);
                return true;
            } catch (NumberFormatException ex) {
                try {
                    Float.parseFloat(str);
                    return true;
                } catch (NumberFormatException exx) {
                    return false;
                }
            }
        }
    }

五、第三方類庫

    /**
     * 判斷一個 string 類型的字符串是不是一個數字
     *
     * <p>
     * commons-lang3 庫 -- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
     * </p>
     *
     * @param str string 類型的字符串
     * @return <code>true</code> 該 string 類型的字符串是數字
     */
    private static boolean judgeByCommonsLong3(final String str) {
        // NumberUtils.isParsable(str)
        // NumberUtils.isDigits(str)
        // 這一個效果好一點
        return NumberUtils.isCreatable(str);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章