Java에서 정규식을 활용해 문자열을 검색할 때, 대소문자를 구분하지 않고 매칭하고 싶은 경우가 자주 있습니다. 예를 들어 'test', 'TEST', 'Test'를 모두 같은 단어로 인식해야 하는 상황이 그렇습니다. 이럴 때 Pattern 클래스의 CASE_INSENSITIVE 플래그를 사용하면 간단하게 해결할 수 있습니다.
Pattern 클래스의 compile() 메서드 이해하기
Pattern 클래스의 compile() 메서드는 두 가지 매개변수를 받을 수 있습니다.
- 정규식 문자열: 매칭에 사용할 정규 표현식을 나타내는 문자열 값입니다.
- 플래그 값: Pattern 클래스가 제공하는 정수형 필드로, 매칭 동작 방식을 지정합니다.
이 중 CASE_INSENSITIVE 필드는 대소문자에 관계없이 문자를 매칭하도록 만들어 주는 플래그입니다. 따라서 compile() 메서드 호출 시 이 플래그를 정규식과 함께 전달하면, 대문자와 소문자 모두 일치하는 것으로 처리됩니다.
예제 1: 대소문자 무시하고 특정 단어 개수 세기
다음 예제는 입력된 문자열에서 'test'라는 단어가 몇 번 등장하는지, 대소문자 구분 없이 카운트합니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input data: ");
String input = sc.nextLine();
// 찾고자 하는 문자에 대한 정규식
String regex = "test";
// CASE_INSENSITIVE 플래그와 함께 정규식 컴파일
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of occurrences: " + count);
}
}실행 결과
Enter input data:
test TEST Test sample data
Number of occurrences: 3'test', 'TEST', 'Test' 세 가지 형태가 모두 매칭되어 총 3회로 카운트된 것을 확인할 수 있습니다. 참고로 원본 코드처럼 플래그를 생략하면 'test'만 매칭되어 결과가 1이 됩니다.
예제 2: 불리언(Boolean) 타입 문자열 검증
다음 예제는 입력받은 문자열이 true 또는 false인지, 역시 대소문자 구분 없이 검증합니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
}
}실행 결과
Enter a string value:
TRUE
Given string is a boolean type'TRUE'라는 대문자 입력도 불리언 타입으로 올바르게 판별되는 것을 볼 수 있습니다.
정리
대소문자 구분 없이 정규식 매칭을 수행하려면 Pattern.compile(regex, Pattern.CASE_INSENSITIVE) 형태로 플래그를 지정하면 됩니다. 이 외에도 Pattern 클래스는 멀티라인 매칭을 위한 MULTILINE, 유니코드 대소문자 무시를 위한 UNICODE_CASE 등 다양한 플래그를 제공하므로, 필요에 따라 비트 연산자(|)로 조합하여 사용할 수 있습니다.