1
考虑这两个例子:当匹配器#找到返回false
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,零次或多次
我的问题是,为什么在正则表达式的情况下=“\ W。*”匹配是不会放弃零长度匹配?
感谢您的快速回复。这意味着如果空字符串与模式相匹配,则零长度只会出现在结果中。所以在我的情况下,“。*”匹配空字符串,但“\ W. *”不匹配。这是我错过的基本的东西。再次感谢。 –