정규식은 패턴에 포함된 특수 구문을 사용하여 다른 문자열이나 문자열 집합을 일치시키거나 찾는 데 도움이 되는 특수 문자 시퀀스입니다.
정규식의 캡처링 그룹은 "()"로 표시되는 단일 단위로 여러 문자를 처리하는 데 사용됩니다. 즉, 괄호 안에 여러 하위 패턴을 배치하면 하나의 그룹으로 처리됩니다.
예를 들어, 패턴 [0-9]는 0에서 9까지의 숫자와 일치하고 패턴 {5}는 모든 문자와 일치합니다. 이 두 가지를 ([0-9]{5})으로 그룹화하면 , 5자리 숫자와 일치합니다.
예시
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your Date of birth: ");
String dob = sc.nextLine();
//Regular expression to accept date in MM-DD-YYY format
String regex = "^(1[0-2]|0[1-9])/ # For Month\n"
+ "(3[01]|[12][0-9]|0[1-9])/ # For Date\n"
+ "[0-9]{4}$ # For Year";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
//Creating a Matcher object
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if(result) {
System.out.println("Given date of birth is valid");
}else {
System.out.println("Given date of birth is not valid");
}
}
} 출력
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid
예시
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.