1.3 正则表达式【匹配数字】

数字匹配符 \d

\d 可以配置 0到9的整数,等价于上一节 中的 [0-9] 。

测试实例

被匹配字符串

private static final String test1 = "a12adf31d2tt";

匹配公式1

匹配公式:

 String expression1 = "\\d";

匹配结果:

1.3 正则表达式【匹配数字】_第1张图片

 


匹配公式2

匹配公式:

 String expression2 = "[0-9]";

匹配结果:

1.3 正则表达式【匹配数字】_第2张图片

注:可以看出匹配公式1和匹配公式2的匹配结果是一样的

匹配公式3

匹配公式

 String expression3 = "\\D";

匹配结果

1.3 正则表达式【匹配数字】_第3张图片


匹配公式4

匹配公式

 String expression4 = "[^0-9]";

匹配结果

1.3 正则表达式【匹配数字】_第4张图片

注:可以看出匹配公式3和匹配公式4匹配结果一致


测试代价【java】

package com.kgo.javaregular.character;

import cn.hutool.core.util.ReUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author keepgoon
 * @Description: TODO
 * @date 2019/10/111:25
 */
public class RE2Test {
    private static Logger log = LoggerFactory.getLogger(RE2Test.class);
    private static final String test1 = "a12adf31d2tt";
    public static void main(String[] args) {
        String expression1 = "\\d";
        String expression2 = "[0-9]";
        String expression3 = "\\D";
        String expression4 = "[^0-9]";

        log.debug("\n===============匹配公式1 =======================");
        find(expression1,test1);
        log.debug("\n===============匹配公式2 =======================");
        find(expression2,test1);
        log.debug("\n===============匹配公式3 =======================");
        find(expression3,test1);
        log.debug("\n===============匹配公式4 =======================");
        find(expression4,test1);

    }
    private static String length(String printStr){
        return  StringUtils.rightPad(printStr,10," ") + " :       {}";
    }
    private static void find(String pattern,String matchedStr){
        log.debug(" 正则表达式 【 {} 】; 被匹配的字符串 【 {} 】" ,pattern,matchedStr);
        log.debug(length("findAll"), ReUtil.findAll(pattern,matchedStr,0));
        log.debug(length("count"), ReUtil.count(pattern,matchedStr));
        log.debug(length("contains"), ReUtil.contains(pattern,matchedStr));
        //log.debug(length("contains"), ReUtil.get);
    }
}

编程技术

编程语言 java
正则匹配 开源工具集  hutool
打印 logback
字符串格式化 lang3

你可能感兴趣的:(正则表达式)