15

我有下一个代码:

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));
        }
    }
}

并有下一个输出:

word
w

但在我看来,它必须是:

word
word

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

4

2 回答 2

17

因为您的模式是非贪婪的,所以它们匹配尽可能少的文本,同时仍然包含匹配项。

去除 ?在第二组,你会得到
word
word word big small

Matcher mtch = Pattern.compile("test is a (\\s*.+?\\s*) word (\\s*.+\\s*)").matcher(test);
于 2012-01-19T18:22:03.400 回答
3

通过使用\\s*它将匹配任意数量的空格,包括 0 个空格。 w匹配 (\\s*.+?\\s*)。为了确保它匹配由空格分隔的单词,请尝试(\\s+.+?\\s+)

于 2012-01-19T18:23:35.993 回答