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

猜你喜欢

转载自blog.csdn.net/weixin_44021334/article/details/134220613