【问题标题】:When Matcher#find returns false当 Matcher#find 返回 false
【发布时间】:2016-01-11 02:03:15
【问题描述】:

考虑这两个例子:

    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 

据此:https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

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

我的问题是为什么在 regex = "\W.*" 的情况下匹配器不提供零长度匹配?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    因为"\W.*" 表示:"\W" - 非单词字符,加上 ".*" - 任何字符零次或多次,所以只有 '@...' 等于此模式 "\W.*",但 "" 不是匹配。

    【讨论】:

    • 感谢您的快速回复。这意味着零长度只会在空字符串与模式匹配时出现在结果中。所以在我的情况下,“.*”匹配空字符串,但“\W.*”不匹配。那是我所缺少的基本东西。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2017-12-29
    • 1970-01-01
    相关资源
    最近更新 更多