English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaのMatcher group()メソッドと例

java.util.regex.Matcher類表示執行各種匹配操作的引擎。該類沒有構造函數,可以使用matches()java.util.regex.Pattern的方法建立/獲取該類的物件。

這個(Matcher)類的group()方法在上一次匹配期間返回匹配的輸入子序列。

例子1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> "
         + "where <b>every</b> alternative <b>word</b> is <b>bold</b>. "
         + "It <i>also</<i>contains <i>italic</<i>words</);
      //正則表達式以匹配粗体標籤的内容
      String regex = "<b>(\\S+);/b>|<i>(\\S+);/i>";
      //パターンオブジェクトの作成
      Pattern pattern = Pattern.compile(regex);
      //文字列内の既にコンパイルされたパターンをマッチング
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group());
      }
   }
}

出力結果

<b>is</b>
<b>example</b>
<b>script</b>
<b>every</b>
<b>word</b>
<b>bold</b>
<i>also</i>
<i>italic</i>

此方法的另一種變體接受表示組的整數變數,其中捕獲的組從1(从左到右)開始索引。

例子2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
   public static void main(String[] args) {
      String regex = "(.*);+);*);
      String input = "This is a sample Text, 1234, with numbers in between.";
      //パターンオブジェクトの作成
      Pattern pattern = Pattern.compile(regex);
      //文字列内の既にコンパイルされたパターンをマッチング
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("match: "+matcher.group(0));
         System.out.println("First group match: "+matcher.group(1));
         System.out.println("Second group match: "+matcher.group(2));
         System.out.println("Third group match: "+matcher.group(3));
      }
   }
}

出力結果

match: This is a sample Text, 1234, with numbers in between.
First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.