一个关于查找数字字符串的Java正则表达式

2023-12-08

我正在网上学习 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+)。如果您想要不同的行为,那么您应该阅读贪婪和非贪婪匹配,或者找到更合适的模式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一个关于查找数字字符串的Java正则表达式 的相关文章

随机推荐