Java中的非贪婪正则表达式

Div*_*ers 10 java regex non-greedy

我有下一个代码:

public static void createTokens(){
    String test = "test is a word word word word big small";
    Matcher mtch = Pattern.compile("test is a (\\s*.+?\\s*) word (\\s*.+?\\s*)").matcher(test);
    while (mtch.find()){
        for (int i = 1; i <= mtch.groupCount(); i++){
            System.out.println(mtch.group(i));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并有下一个输出:

word
w
Run Code Online (Sandbox Code Playgroud)

但在我看来,它一定是:

word
word
Run Code Online (Sandbox Code Playgroud)

有人请解释我为什么这样?

the*_*ber 11

因为你的模式不是贪婪的,所以它们尽可能地匹配尽可能少的文本,同时仍然包含匹配.

除掉 ?在第二组中,你会得到
单词
单词大小

Matcher mtch = Pattern.compile("test is a (\\s*.+?\\s*) word (\\s*.+\\s*)").matcher(test);
Run Code Online (Sandbox Code Playgroud)