java.time.Matcher.end(int group)方法

java.time.Matcher.end(int group)方法返回在上一个匹配操作期间由给定组捕获的子序列的最后一个字符之后的偏移量。

声明

以下是java.time.Matcher.end(int group)方法的声明。

public int end(int group)

参数

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

返回值

组捕获的最后一个字符后的偏移量,如果匹配成功但组本身不匹配,则返回-1

异常

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

示例

以下示例显示了java.time.Matcher.end(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 offset after the last character matched.
         System.out.println("Second Capturing Group, (foo) Match String end(): "+matcher.end(1));
      }      
   }
}

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

Second Capturing Group, (foo) Match String end(): 3
Second Capturing Group, (foo) Match String end(): 9
Second Capturing Group, (foo) Match String end(): 14

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