首页 > 解决方案 > 为什么 (/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");
      }
   }
}

标签: javaregex

解决方案


这是因为*执行贪心匹配,它总是尝试尽可能多地匹配,同时仍然允许整个表达式匹配。

.*匹配任何字符的 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

演示:https ://ideone.com/AfE7Jn


推荐阅读