java.util.regex.MatchResult.group() 方法



描述

java.time.MatchResult.group() 方法返回前一個匹配項匹配的輸入子序列。

宣告

以下是 java.time.MatchResult.group() 方法的宣告。

String group()

返回值

前一個匹配項匹配的(可能是空的)字串形式的子序列。

異常

  • IllegalStateException - 如果尚未嘗試匹配,或如果前一個匹配操作失敗。

示例

以下示例演示了 java.time.MatchResult.group() 方法的用法。

package com.tutorialspoint;

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

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the input subsequence matched by the previous match.
         System.out.println("First Capturing Group - Match String: "+result.group());     
      }
   }
}

讓我們編譯並執行上述程式,將產生以下結果 −

First Capturing Group - Match String: This is a sample Text, 1234, with numbers in between.
javaregex_matchresult.htm
廣告
© . All rights reserved.