考虑以下两个例子:
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. *”的情况下匹配器没有给出零长度匹配?
答案 0 :(得分:1)
因为"\W.*"
表示:"\W"
- 非单词字符加上".*"
- 任意字符为零或更多次,所以只有'@...'
等于此模式{{1 }},但"\W.*"
没有匹配。