하위 표현식/메타 문자 "re{ n}"은 이전 표현식의 n번 발생과 정확히 일치합니다.
예시 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "to{1}";
String input = "Welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} 출력
Number of matches: 2
예시 2
다음 Java 프로그램은 사용자로부터 연령 값을 읽어 두 자리 숫자만 허용합니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\d{2}";
System.out.println("Enter your age:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.matches()) {
System.out.println("Age value accepted");
} else {
System.out.println("Age value not accepted");
}
}
} 출력 1
Enter your age: 25 Age value accepted
출력 2
Enter your age: 2252 Age value not accepted
출력 3
Enter your age: twenty Age value not accepted