目录

Java Regex - 捕获组( Capturing Groups)

捕获组是将多个字符视为一个单元的一种方法。 它们是通过将要分组的字符放在一组括号中来创建的。 例如,正则表达式(dog)创建包含字母“d”,“o”和“g”的单个组。

捕获组通过从左到右计算它们的左括号来编号。 在表达式((A)(B(C)))中,例如,有四个这样的组 -

  • ((A)(B(C)))
  • (A)
  • (B(C))
  • (C)

要查找表达式中存在多少个组,请在匹配器对象上调用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
↑回到顶部↑
WIKI教程 @2018