添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

数字类型的判断是项目里常见的场景,相比一大串的非空,instanceof 以及大于小于0的判断,我更倾向于使用工具类 StringUtils 或者 正则表达式 来实现功能,追求代码的简洁和高效。

你可能需要的博客:

一、StringUtils 方法

isNumeric() 和 isNumericSpace() 都属于 StringUtils,区别也就在字面意思里:对 Space(空格)的处理方式不用。

使用 StringUtils 类,需要在 pom.xml 中引入“commons-lang3”依赖:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>

1. StringUtils.isNumeric()

目的:用来判断传入字符串是否为正整数。

    @Test
    void test_isNumeric(){
        System.out.println("正整数:" + StringUtils.isNumeric("123"));         // true
        System.out.println("零:" + StringUtils.isNumeric("0"));               // true
        System.out.println("负整数:" + StringUtils.isNumeric("-123"));        // false
        System.out.println("小数:" + StringUtils.isNumeric("1.23"));          // false
        System.out.println("null:" + StringUtils.isNumeric(null));            // false
        System.out.println("空格:" + StringUtils.isNumeric(" "));             // false
        System.out.println("空字符串:" + StringUtils.isNumeric(""));           // false
        System.out.println("数字带空格:" + StringUtils.isNumeric("1 2 3"));    // false
  • StringUtils.isNumeric() 源码 

         isNumeric() 会遍历 CharSequence 字符并逐一校验,所以就需要参数字符串的每一位都满足【十进制数字】这一规则,所以,像“-123”或“+123”这样认知上为数字的字符串验证结果是 False。

    /** StringUtils.isNumeric() 源码 */
    public static boolean isNumeric(CharSequence cs) {
        // 1. 校验:'',空和null
        if (isEmpty(cs)) {
            return false;
        } else {
            int sz = cs.length();
            for(int i = 0; i < sz; ++i) {
                // 2. 校验:判断字符的一般类别是否为【十进制数字】
                if (!Character.isDigit(cs.charAt(i))) {
                    return false;
            return true;

        如果进一步 DeBug 进入 Character.isDigit() 方法,会发现 isDigit() 属于 java.lang.Character,也就是说:isNumeric() 归根结底用的还是 Java 自带的字符判断方法。

    /** 当前方法属于 java.lang.Character */    
    public static boolean isDigit(char ch) {
        return isDigit((int)ch);

        进一步 DeBug 进入  isDigit() , 核心代码是 Character.getType() 方法,它的作用就是:判断字符的一般类别是否为【十进制数字】(十进制数字返回9,其他类型自己看源码)。

    /** 当前方法属于 java.lang.Character */
    public static boolean isDigit(int codePoint) {
        // getType() 目的是获取 codePoint 的类型
        // Character.DECIMAL_DIGIT_NUMBER = 9
        return getType(codePoint) == Character.DECIMAL_DIGIT_NUMBER;

2. StringUtils.isNumericSpace()

        目的:用来判断传入字符串是否为正整数,字符串里的空格不影响结果。

    @Test
    void test_isNumericSpace(){
        System.out.println("正整数:" + StringUtils.isNumericSpace("123"));         // true
        System.out.println("零:" + StringUtils.isNumericSpace("0"));               // true
        System.out.println("负整数:" + StringUtils.isNumericSpace("-123"));        // false
        System.out.println("小数:" + StringUtils.isNumericSpace("1.23"));          // false
        System.out.println("null:" + StringUtils.isNumericSpace(null));            // false
        System.out.println("空格:" + StringUtils.isNumericSpace(" "));             // true
        System.out.println("空字符串:" + StringUtils.isNumericSpace(""));          // true
        System.out.println("数字带空格:" + StringUtils.isNumericSpace("1 2 3"));   // true
  • StringUtils.isNumericSpace() 源码

        isNumericSpace()与isNumeric()的区别在于,isNumericSpace() 对空格以及空字符串的处理结果也为 True,就算是字符串内部的空格也会自动忽略掉,这些改变在源码里可以清晰的看出差别。

    /** StringUtils.isNumericSpace() 源码 */
    public static boolean isNumericSpace(CharSequence cs) {
        // 1. 这里没有 isEmpty() 判空,只校验了 null
        if (cs == null) {
            return false;
        } else {
            int sz = cs.length();
            for(int i = 0; i < sz; ++i) {
                // 2. 这里排除了“空格”的情况,认为不为正整数且同时不为''时,才返回 False
                if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
                    return false;
            return true;

        其他部分源码与分析与isNumeric()一脉相承。

二、正则表达式

        StringUtils 的方法有自己的局限性,它只能判断正整数,其他的数字类型,如:负整数,浮点数...,使用正则表达式是常用的手段。

  • 预编译的正则写法
    // regexRule 是正则规则
    private static final Pattern pattern = Pattern.compile(regexRule);
    @Test
    void test_pattern(){
        Matcher mat = pattern.matcher("-123");
        System.out.println("正则匹配结果:" + mat);
  • 数字有关的正则表达式
说明正则表达式
非负整数(正整数 + 0)^\d+$
正整数^[0-9]*[1-9][0-9]*$
非正整数(负整数 + 0)^((-\d+)|(0+))$
负整数^-[0-9]*[1-9][0-9]*$
浮点数^(-?\d+)(\.\d+)?$
非负浮点数(正浮点数 + 0)^\d+(\.\d+)?$
非正浮点数(负浮点数 + 0)^((-\d+(\.\d+)?)|(0+(\.0+)?))$
......
<groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> StringUtils.i
可以使用正则表达式校验字符串是否为正数或两位小数。下面是一个例子: public static boolean isPositiveNumberOrTwoDecimalPlaces(String str) { String pattern = "^[0-9]+\\.{0,1}[0-9]{0,2}$"; return str.matches(pattern); 在上面的代码中...
文章目录引言一、判断字符串是否为数字1.1 第三方包StringUtils.isNumeric1.2 Java自带方法Character.isDigit1.3 正则表达式二、将字符串转化为数字2.1 整数2.2 小数参考  在开发过程中经常需要判断字符串是否为数字,并将字符串转换为数字类型,本篇文章总结一下常用方法。 一、判断字符串是否为数字 1.1 第三方包StringUtils.isNumeric  使用第三方包org.apache.commons.lang3中的StringUtils.isNum
```java public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; return str.matches("\\d+"); 其中,参数str为需要判断的字符串。如果该字符串为空或长度为0,则返回false。使用String的matches()方法,传入正则表达式"\\d+",如果字符串匹配成功则返回true,否则返回false。 异常:Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 已解决 359300 Python爬虫HTTP异常:rllib.error.HTTPError: HTTP Error 418,伪装User-Agent以及fake-useragent插件的妙用 codes23457789: 不错 不粗 启动 Tomcat 遇到 Neither the JAVA_HOME nor the JRE_HOME environment variable is defined 问题,已解决 学废的秃头少女: 终于解决了 启动 Tomcat 遇到 Neither the JAVA_HOME nor the JRE_HOME environment variable is defined 问题,已解决 爱新觉罗启钰: 您好。安装tomcat是需要再安装一个Java程序吗? 异常:java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding 风度翩翩609: 确实最简单快捷有效表情包 项目install异常:Failed to execute goal on project xx: Could not resolve dependencies for project com.xx Redis异常:MISCONF Redis is configured to save RDB snapshots, but currently not able to persist on disk 枚举工具类,生产上Enum的常用方法