Java正则的贪婪和非贪婪模式

javabloger 2019-06-25

定义

  • 贪婪模式:匹配尽可能多的字符
  • 非贪婪模式:匹配尽可能少的字符

Java的正则表达式中,通过在修饰匹配次数的符号后面加一个?,即非贪婪模式,默认情况下是贪婪模式。

表示匹配次数的符号有:

.?        # 任意字符匹配1次或0次
.*        # 任意字符匹配0次或多次
.+        # 任意字符匹配1次或多次
.{n}    # 任意字符匹配n次
.{n,}    # 任意字符匹配至少n次
.{n,m}    # 任意字符匹配至少n次,至多m次

代码

public static void main(String[] args) {
        String input = "aaaabc";


        String regex1 = "a{2,3}";               // 贪婪模式
        Pattern p1 = Pattern.compile(regex1);
        Matcher m1 = p1.matcher(input);
        while (m1.find()) {
            System.out.println(m1.group());
        }

        System.out.println("------------------");

        String regex2 = "a{2,3}?";              // 非贪婪模式
        Pattern p2 = Pattern.compile(regex2);
        Matcher m2 = p2.matcher(input);
        while (m2.find()) {
            System.out.println(m2.group());
        }

    }

输出:

aaa
------------------
aa
aa

原文链接

https://segmentfault.com/a/11...

相关推荐

jyj00 / 0评论 2020-01-29