java - 为什么 (/d+) 正则表达式只占用一位数字?
问题描述
所以我正在浏览一些解释 Java 中正则表达式的代码,特别是捕获组,这就是正则表达式 - (.*)(\d+)(.\)
。
现在第二组只会打印出一个数字,这是 + 量词所占用的最少数量,如果我用 * 替换它,它将占用零位,这是 * 量词所占用的最少数量。所以我看到了发生了什么,但我不明白为什么它要列出事物的数量而不是可能的最高数量。
import java.util.regex.Pattern;
public class RegexMatches {
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
解决方案
这是因为*
执行贪心匹配,它总是尝试尽可能多地匹配,同时仍然允许整个表达式匹配。
.*
匹配任何字符的 0 个或多个,并且它可以匹配的最多是"This order was placed for QT300"
因为它必须离开"0"
以匹配\d+
(一个或多个数字)。
相比之下,勉强匹配总是会尝试尽可能少地匹配,同时仍然允许匹配整个表达式。您可以使用*?
而不是*
勉强匹配。
对于字符串"This order was placed for QT3000! OK?"
,任何字符的零个或多个可以匹配的最少是"This order was placed for QT"
,因为接下来的四个字符是数字并且可以匹配\d+
。
final String pattern = "(.*?)(\\d+)(.*)";
使用上述模式将产生以下输出:
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
推荐阅读
- javascript - 如何在 res.download 选项中提及文件大小
- android - 更新 android 应用程序的包名称
- java - Java中的多个字符
- xamarin.forms - Xamarin.Forms 编译绑定生成错误
- azure-ad-b2c - 避免在登录后针对联合身份提供者验证会话
- data-structures - 反转时间复杂度 O(1) 的链表
- sdn - Ryu SDN 多路径
- python - Python 。唯一订购商品列表
- javascript - 如何在 Google Earth Engine 中累积 CHIRPS 每日提供的每日降雨量?
- sql - 按组计算唯一值的数量