我正在网上学习 Java 正则表达式教程,并对一个小程序感到困惑。
// String to be scanned to find the pattern.
String line = "This order was places 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) );
}
打印出来的结果是:
Found value: This order was places for QT3000! OK?
Found value: This order was places for QT300
Found value: 0
我不知道为什么 group(1) 的值是上面的值?为什么它在“QT3000”的最后一个零之前停止?
非常感谢!
最佳答案
第一组(.*)
(这是索引1 - 索引0是整个正则表达式)是贪婪匹配。它尽可能多地捕捉,同时让整体表达仍然匹配。因此,它最多可以占用字符串中的第二个 0
,仅留下 0
来匹配 (\\d+)
。如果您想要不同的行为,那么您应该阅读贪婪和非贪婪匹配,或者找到更合适的模式。
关于regex - 一个关于查找数字字符串的Java正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434913/