gpt4 book ai didi

java - 为什么 Java 正则表达式 "matches"与 "find"在使用非贪婪模式时得到不同的匹配?

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:59 24 4
gpt4 key购买 nike

<分区>

因此,我遇到了一个错误,该错误是由期望 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());

输出

Matches complete string? true
What was the match? 'START'===stageType?'active':''
Found a match in at least part of the string? true
What was the match? 'START'

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com