Java에서 제공하는 greedy 수량자를 사용하면 표현식의 여러 항목을 일치시킬 수 있습니다. 어디,
-
Exp{n}은 표현식 exp가 정확히 n번 발생하도록 합니다.
-
Exp{n,}는 표현식 exp가 n번 이상 발생하도록 합니다.
-
Exp{n, m}은 표현식 exp가 최소 n번, 최대 m번 발생하도록 합니다.
예시 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { //regular expression to accept 5 letter word String regex = "\\w{5}"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println(input[i]+": accepted"); } else { System.out.println(input[i]+": not accepted"); } } } }
출력
Enter 5 input strings: rama raja raghu megha malya rama: not accepted raja: not accepted raghu: accepted megha: accepted malya: accepted
예시 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { //Regular expression to match a string of non-word with length 2 to 6 String regex = "\\W{2,6}"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println(input[i]+" matched"); } } } }
출력 1
Enter 5 input strings: hello how are you #$#% # #$@%%#&#& sample text #$#% matched #$@%%#&#& matched
예시 3
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 = "[a-zA-Z]{1,20}"; Scanner sc = new Scanner(System.in); System.out.println("Enter students name:"); String name = sc.nextLine(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(name); if(m.matches()) { System.out.println("Name is appropriate"); } else { System.out.println("Name is inappropriate"); } } }
출력
Enter students name: Mouktika Name is appropriate