Java 当Matcher#find返回false时

Java 当Matcher#find返回false时,java,regex,Java,Regex,考虑以下两个例子: testFind("\\W.*", "@ this is a sentence"); testFind(".*", "@ this is a sentence"); 这是我的testFind方法 private static void testFind(String regex, String input) { Pattern pattern = Pattern.compile(regex); Matcher matcher = patte

考虑以下两个例子:

    testFind("\\W.*", "@ this is a sentence");
    testFind(".*", "@ this is a sentence");
这是我的testFind方法

 private static void testFind(String regex, String input) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    int matches = 0;
    int nonZeroLengthMatches = 0;

    while (matcher.find()) {
        matches++;
        String matchedValue = matcher.group();
        if (matchedValue.length() > 0) {
            nonZeroLengthMatches++;
        }
        System.out.printf("Matched startIndex= %s, endIndex= %s, value: '%s'\n",
                matcher.start(), matcher.end(), matchedValue);

    }

    System.out.printf("Total non zero length matches = %s/%s \n", nonZeroLengthMatches, matches);
}
以下是输出:

 ---------------------
   Regex: '\W.*', Input: '@ this is a sentence'
   Matched startIndex= 0, endIndex= 20, value: '@ this is a sentence'
   Total non zero length matches = 1/1 
   ---------------------
   Regex: '.*', Input: '@ this is a sentence'
   Matched startIndex= 0, endIndex= 20, value: '@ this is a sentence'
   Matched startIndex= 20, endIndex= 20, value: ''
   Total non zero length matches = 1/2 
据此:

贪婪量词 ..... X*X,零次或多次


我的问题是,为什么在regex=“\W.*”的情况下,matcher不提供零长度匹配

因为
“\W.*”
的意思是:
“\W”
-一个非单词字符,加上
“*”
-任何字符零次或多次,所以只有
“@…”
等于此模式
“\W.*”
,但
不匹配。

感谢您的快速回复。这意味着只有当空字符串与模式匹配时,结果中才会出现零长度。所以在我的例子中,“*”匹配空字符串,但“\W.*”不匹配。这是我错过的最基本的东西。再次感谢。