java.util.regex.Matcher 클래스는 다양한 일치 작업을 수행하는 엔진을 나타냅니다. 이 클래스에 대한 생성자가 없습니다. java.util.regex.Pattern 클래스의 match() 메소드를 사용하여 이 클래스의 객체를 생성/얻을 수 있습니다.
그룹() 이 (Matcher) 클래스의 메소드는 마지막 일치 중에 일치하는 입력 하위 시퀀스를 반환합니다.
예시 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</p>";
//Regular expression to match contents of the bold tags
String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
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 = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between.";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
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.