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> 예제</b> HTML <b>스크립트</b> "
         + "where <b>모든</b> 대체 단어</b>은 <b>굵은</b>. "
         + "It <i>도</i> 이탈릭을 포함합니다 </i> 단어</p>";
      //정규 표현식은 굵은 태그의 내용을 매칭하도록 합니다
      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>는</b>
<b>예제</b>
<b>스크립트</b>
<b>모든</b>
<b>단어</b>
<b>粗体</b>
<i>도</i>
<i>이탈릭</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.