문자 클래스를 사용하면 고정된 문자 집합에서 단일 문자를 허용할 수 있습니다. 예를 들어,
-
표현 "[tmp] "는 문자 t 또는, m 또는, p와 일치합니다.
-
표현 "[^tp] "는 t 또는 p 이외의 문자와 일치합니다.
예시 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();
//Regular expression to match the characters t or, m or, p
String regex = "[tmp]";
//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 hello how are you welcome to tutorialspoint Occurrences :6
예시 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 = "[^abcdef]";
//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 Hello how are you welcome to tutorialspoint Occurrences :36