Java 정규식의 문자 클래스는 대괄호 "[ ]"를 사용하여 정의되며, 이 하위 표현식은 지정된 또는 가능한 문자 집합의 단일 문자와 일치합니다. 예를 들어 정규식 [abc]는 단일 문자 a 또는, b 또는 c와 일치합니다.
문자 클래스의 공용체 변형을 사용하면 지정된 범위 중 하나의 문자와 일치시킬 수 있습니다. 즉, 표현식 [a-z[0-9]]는 작은 알파벳(a-z) 또는 숫자(0-9)인 단일 문자와 일치합니다. ).
예
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[a-z[0-9]]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
count++;
}
System.out.println("Number characters from the ranges (a-z or 0-9): "+count);
}
} 출력
Enter input text: sample DATA 12345 Number characters from the ranges (a-z or 0-9): 11