JAVA判断是字符串是否可转换成数字(判断字符串是否为数字样式)

使用正则表达式来验证

    /**
     * 利用正则表达式判断字符串是否是数字
     * 数字\d+(|(\.\d+))
     * 整数\d+或[0-9]+
     * 负数-\d+
     * @param str
     * @return
     */
    public boolean isNum(String str){
        Pattern pattern = Pattern.compile("\d+(|(\.\d+))");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    } 

 

字符串转换

    public static boolean isNum(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

 

posted on 2022-04-08 15:46  骑着母猪去打猎  阅读(523)  评论(0)    收藏  举报