Javaregex 简明教程

Java Regex - Capturing Groups

捕获组是一种将多个字符视为单个单位的方法。它们是通过将待分组的字符置于一组圆括号内创建的。例如,正则表达式 (dog) 创建单个组,其中包含字母“d”、“o”和“g”。

捕获组通过从左到右计算其左括号进行编号。例如,在表达式 A)(B© 中,存在四个这样的组 -

  1. A)(B©

  2. (A)

  3. (B©)

  4. ©

若要找出表达式中有多少组,请对匹配器对象调用 groupCount 方法。groupCount 方法返回一个 int,显示匹配器模式中存在的分组数。

还有一个特殊的组,组 0,它始终代表整个表达式。此组不包括在 groupCount 报告的总数中。

Example

以下示例说明如何从给定的字母数字字符串中找到数字字符串 -

import java.util.regex.Matcher;
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");
      }
   }
}

这会产生以下结果 −

Output

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0