程序员Java

Java利用正则判断字符串是否为正整数或者浮点数

2019-11-25  本文已影响0人  仲冬初七
    /**
     * 判断字符串是否为正整数或者浮点数
     * 1.11 -> true
     * 1 -> true
     * -1 -> false
     * 1a -> false
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        // 判断正整数正则
        Pattern patternInteger = Pattern.compile("^\\d+(\\.\\d+)?$");
        // 判断浮点数正则
        Pattern patternFloat = Pattern.compile("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
        return patternFloat.matcher(str).matches() || patternInteger.matcher(str).matches();
    }
上一篇 下一篇

猜你喜欢

热点阅读