English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
부표현식/정수자 "re {n}"는 이전 표현식이 나타나는 n번째 등장을 정확히 일치시킵니다.
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 w3codebox"; 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
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("您的年龄을 입력하세요:"); 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"); } } }
您的年龄을 입력하세요: 25 Age value accepted
您的年龄을 입력하세요: 2252 Age value not accepted
您的年龄을 입력하세요: twenty Age value not accepted