Java正则表达式捕获组

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

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

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

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

还有一个特殊组,即组0,它始终代表整个表达式。 该组未包含在groupCount报告的总数中。

示例

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

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");
      }
   }
}

执行上面示例代码,得到以下结果:

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

上一篇:Java正则表达式简介

下一篇:Java正则表达式MatchResult的接口

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程