문자 범위를 일치시키려면, 즉 시퀀스에서 지정된 두 문자 사이의 모든 문자를 일치시키려면 문자 클래스를
로 사용할 수 있습니다.[a-z]
-
표현 “[a-zA-Z] "는 모든 영어 알파벳을 허용합니다.
-
표현 “[0-9&&[^35]] "는 3과 5를 제외한 숫자를 허용합니다.
예시 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^[a-zA-Z0-9]*$";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
} 출력 1
Enter a String Hello Match occurred
출력 2
Enter a String sample# Match not occurred
예시 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "[0-9&&[^35]]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences :"+count);
}
} 출력
Enter a String 111223333555689 Occurrences :8