Java 正则表达式重复匹配篇

重复匹配

  • * 可以匹配任意个字符,包括0个字符。
  • + 可以匹配至少一个字符。
  • ? 可以匹配0个或一个字符。
  • {n} 可以精确指定 n 个字符。
  • {n,m} 可以精确匹配 n-m 个字符。你可以是 0 。

匹配任意个字符

匹配 D 开头,后面是任意数字的字符,

复制代码
        String regexU1 = "D\\d*";
        System.out.println("DD".matches(regexU1));// false
        System.out.println("D1".matches(regexU1));// true
        System.out.println("D202".matches(regexU1));// true
        System.out.println("D88888888".matches(regexU1));// true

匹配至少一个字符

匹配 D 开头,后面至少是一位数字的字符,

复制代码
        String regexU2 = "D\\d+";
        System.out.println("D".matches(regexU2));// false
        System.out.println("D1".matches(regexU2));// true
        System.out.println("D202".matches(regexU2));// true
        System.out.println("D88888888".matches(regexU2));// true

匹配 0 个或一个字符

匹配 D 开头,后面是 0个或一个数字的字符,

复制代码
        String regexU3 = "D\\d?";
        System.out.println("D".matches(regexU3));// true
        System.out.println("D1".matches(regexU3));// true
        System.out.println("D22".matches(regexU3));// false
        System.out.println("D88888888".matches(regexU3));// false

匹配 n 个字符

匹配 D 开头,后面 3 个数字的字符,

复制代码
        String regexU4 = "D\\d{3}";
        System.out.println("D".matches(regexU4));// false
        System.out.println("D1".matches(regexU4));// false
        System.out.println("D22".matches(regexU4));// false
        System.out.println("D301".matches(regexU4));// true
        System.out.println("D3004".matches(regexU4));// false

匹配 n-m 个字符

匹配 D 开头,后面是 3-5 位数字的字符,

复制代码
        String regexU5 = "D\\d{3,5}";
        System.out.println("D".matches(regexU5));// false
        System.out.println("D1".matches(regexU5));// false
        System.out.println("D22".matches(regexU5));// false
        System.out.println("D333".matches(regexU5));// true
        System.out.println("D4000".matches(regexU5));// true
        System.out.println("D55555".matches(regexU5));// true
        System.out.println("D666666".matches(regexU5));// false
相关推荐
间彧几秒前
Spring Boot项目中如何自定义线程池
java
间彧21 分钟前
Java线程池详解与实战指南
java
用户2986985301429 分钟前
Java 使用 Spire.PDF 将PDF文档转换为Word格式
java·后端
渣哥38 分钟前
ConcurrentHashMap 1.7 vs 1.8:分段锁到 CAS+红黑树的演进与性能差异
java
间彧1 小时前
复用线程:原理详解与实战应用
java
咖啡Beans2 小时前
使用OpenFeign实现微服务间通信
java·spring cloud
我不是混子2 小时前
说说单例模式
java
间彧5 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧5 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java