因此,我遇到了一个错误,该错误是由于期望 matches() 方法找到与使用 find() 完全相同的匹配项而引起的。通常是这种情况,但看起来如果非贪婪模式可以延伸到贪婪地接受整个字符串,那么它是允许的。这看起来像是 Java 中的一个错误。我错了吗?我在文档中没有看到任何表明这种行为的内容。
Pattern stringPattern = Pattern.compile("'.*?'");
String nonSingleString = "'START'===stageType?'active':''";
Matcher m1 = stringPattern.matcher(nonSingleString);
boolean matchesCompleteString = m1.matches();
System.out.println("Matches complete string? " + matchesCompleteString);
System.out.println("What was the match? " + m1.group()); //group() gets the string that matched
Matcher m2 = stringPattern.matcher(nonSingleString);
boolean foundMatch = m2.find(); //this looks for the next match
System.out.println("Found a match in at least part of the string? " + foundMatch);
System.out.println("What was the match? " + m2.group());
Outputs
匹配完整的字符串?真的
比赛结果如何? 'START'===stageType?'active':''
至少在字符串的一部分中找到匹配项?真的
比赛结果如何? '开始'
这是完全有道理的。
The matches(...)
方法必须尝试消耗整个字符串,因此即使使用非贪婪模式也是如此。
The find(...)
方法可能会找到一个子字符串,因此如果找到任何匹配的子字符串,它就会在该点停止。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)