所以我遇到了一个错误,因为期望match()方法找到与使用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());
Run Code Online (Sandbox Code Playgroud)
输出
匹配完整的字符串?真正的
是什么比赛?'START'=== stageType?'active':''
在字符串的至少一部分找到匹配项?真正的
是什么比赛?'开始'
这很有道理.
该matches(...)方法必须尝试使用整个字符串,因此即使使用非贪婪模式也是如此.
该find(...)方法可以找到子字符串,因此如果找到任何匹配的子字符串,它将在该点处停止.