java中判断字符串是否为数字的方法的几种方法

来源:互联网 发布:浪潮gs软件下载 编辑:程序博客网 时间:2024/05/14 15:31

前言

网上有很多这种资料,之所以我又写一篇,是今天在实践网上给的方法时,发现很多bug。
所以我就自己总结下。同时也请那些在复制粘贴别人的东西时,最好实践下。
不实践的话,自己得到的可能是错误的方法,同时也误导他人!

用JAVA自带的函数

    public static boolean isNumericZidai(String str) {        for (int i = 0; i < str.length(); i++) {            System.out.println(str.charAt(i));            if (!Character.isDigit(str.charAt(i))) {                return false;            }        }        return true;    }

其中Character.isDigit方法:确定或判断指定字符是否是一个数字。

测试方法:

    public static void main(String[] args) {        double aa = -19162431.1254;        String a = "-19162431.1254";        String b = "-19162431a1254";        String c = "中文";        System.out.println(isNumericzidai(Double.toString(aa)));        System.out.println(isNumericzidai(a));        System.out.println(isNumericzidai(b));        System.out.println(isNumericzidai(c));    }

结果显示:

falsefalsefalsefalse

这种方法显然不能判断 负数。

用正则表达式

    public static boolean isNumericzidai(String str) {        Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");        Matcher isNum = pattern.matcher(str);        if (!isNum.matches()) {            return false;        }        return true;    }

网上给出的最好的方法,可惜还是错误;首先正则表达式-?[0-9]+.?[0-9]+这里就错误
网上说:可匹配所有数字。
比如:

        double aa = -19162431.1254;        String a = "-19162431.1254";        String b = "-19162431a1254";        String c = "中文";        System.out.println(isNumericzidai(Double.toString(aa)));        System.out.println(isNumericzidai(a));        System.out.println(isNumericzidai(b));        System.out.println(isNumericzidai(c));

结果

falsetruetruefalse

正确的正则表达式是:-?[0-9]+\\.?[0-9]*,点号.,是匹配任意字符,需要进行转义。


注意:感谢网友留言提示了一个错误,之前我的正则表达式是这么写的:
-?[0-9]+\\.?[0-9]+,这种正则表达式在匹配0-9的正负数时,会出错,这是因为该表达式最后是+,表示的是匹配前一个字符1次或无限次。
也就是说在匹配一位的时候,会出现错误。所以改为*,表示匹配前一位字符0次或无限次

System.out.println(isNumeric("9"));

结果为

true

于是我们改成:

    public static boolean isNumericzidai(String str) {        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");        Matcher isNum = pattern.matcher(str);        if (!isNum.matches()) {            return false;        }        return true;    }

执行上面代码结果:

falsetruefalsefalse

可是为什么double aa = -19162431.1254;没有匹配为true呢?
原来当数字位数很长时,系统会自动转为科学计数法。所以aa=-1.91624311254E7.
所以我们需要使用java专门用于商业精度计数的类 BigDecimal.
我们需要new BigDecimal(str),但是呢,如果str为中文,会报异常。所以我用try catch捕捉异常。

正确的通用代码(传入包含中文、负数、位数很长的数字的字符串也能正常匹配):

    /**     * 匹配是否包含数字     * @param str 可能为中文,也可能是-19162431.1254,不使用BigDecimal的话,变成-1.91624311254E7     * @return     * @author yutao     * @date 2016年11月14日下午7:41:22     */    public static boolean isNumeric(String str) {        // 该正则表达式可以匹配所有的数字 包括负数        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");        String bigStr;        try {            bigStr = new BigDecimal(str).toString();        } catch (Exception e) {            return false;//异常 说明包含非数字。        }        Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配        if (!isNum.matches()) {            return false;        }        return true;    }

使用org.apache.commons.lang

public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.null will return false. An empty String ("") will return true. StringUtils.isNumeric(null)   = false StringUtils.isNumeric("")     = true StringUtils.isNumeric("  ")   = false StringUtils.isNumeric("123")  = true StringUtils.isNumeric("12 3") = false StringUtils.isNumeric("ab2c") = false StringUtils.isNumeric("12-3") = false StringUtils.isNumeric("12.3") = falseParameters:str - the String to check, may be null Returns:true if only contains digits, and is non-null

第三种我没有测试,网上说,也不能判断负数。
又因为使用第三方的包,我懒得用,java原生就很好了。


总结下来,肯定是使用第二种正则表达式计算啦!正则表达式用对地方啦,就不慢!
动不动就说正则太慢的人,是玩不6正则表达式的!

3 0