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

2019-10-16 22:19:28

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.yiibai;

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