여러 문자를 그룹으로 캡처하여 단일 단위로 취급할 수 있습니다. 이 문자들을 괄호 안에 넣으면 됩니다.
groupCount()를 사용하여 현재 일치하는 그룹의 수를 계산할 수 있습니다. Matcher 클래스의 메소드 이 메서드는 현재 일치하는 캡처 그룹의 수를 계산하고 반환합니다.
예시
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String str1 = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>ever</b> alternative <b>word</b> is <b>bold</b></p>."; //Regular expression to match contents of the bold tags String regex = "(t(\\S+)t)(\\s)"; String str = "the words tit tat tweet tostff tact that tilt text. start and end with the letter t "; //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(0)); } System.out.println("Total capturing groups: "+matcher.groupCount()); } }
출력
tit tat tweet tact that tilt text tart Total capturing groups: 3