【发布时间】: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.*" 的情况下匹配器不提供零长度匹配?
【问题讨论】: