java.util.regex.Matcher.start(int group)方法

java.util.regex.Matcher.start(int group)方法返回在上一个匹配操作期间由给定组捕获的子序列的起始索引。

声明

以下是java.util.regex.Matcher.start(int group)方法的声明。

public int start(int group)

参数

  • group - 此匹配器模式中捕获组的索引。

返回值

组捕获的第一个字符的索引,如果匹配成功但组本身不匹配,则返回-1。

异常

  • IllegalStateException - 如果尚未尝试匹配,或者上一个匹配操作失败。
  • IndexOutOfBoundsException - 如果模式中没有具有给定索引的捕获组。

示例

以下示例显示了java.util.regex.Matcher.start(int group)方法的用法。

package com.zaixian;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);

      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);

      while(matcher.find()) {
      //Prints the start index of the subsequence captured by the given group.
         System.out.println("Second Capturing Group, (foo) Match String start(): 
            "+matcher.start(1));
      }      
   }
}

编译并运行上面的程序,这将产生以下结果 -

Second Capturing Group, (foo) Match String start(): 0
Second Capturing Group, (foo) Match String start(): 6
Second Capturing Group, (foo) Match String start(): 12

上一篇: Java正则表达式Matcher类 下一篇: Java正则表达式PatternSyntaxException类