POSIX 문자 클래스 \p{Lu}는 영문 대문자(Upper case letter)와 일치하는 정규식 패턴입니다. Java에서 이 클래스를 활용하면 문자열에 포함된 대문자를 찾거나 개수를 세고, 조건에 맞는 문자열을 걸러내는 작업을 간단하게 처리할 수 있습니다.
예제 1 – 문자열에서 대문자 개수 세기
다음 예제는 Scanner로 사용자에게 문자열을 입력받은 뒤, \p{Lu} 패턴과 일치하는 대문자의 개수를 세어 출력합니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example1 {
public static void main(String args[]) {
// 사용자로부터 문자열 입력받기
System.out.println("Enter a string");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// 정규식 정의
String regex = "\\p{Lu}";
// 정규식 컴파일
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of capital characters: "+count);
}
}실행 결과
Enter a string Hello HOW are YOU Number of capital characters: 7
입력 문자열 "Hello HOW are YOU"에는 H, O, W, Y, U 등 총 7개의 대문자가 포함되어 있으므로 결과가 7로 출력됩니다.
예제 2 – 대문자를 포함하는 문자열 필터링
이번 예제는 정규식 ^.*\p{Lu}.*$를 사용해 여러 입력 문자열 중 최소 한 개 이상의 대문자를 포함하는 문자열만 골라냅니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example2 {
public static void main(String args[]) {
// 대문자 포함 여부를 검사하는 정규식
String regex = "^.*\\p{Lu}.*$";
// 입력 데이터 받기
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();
}
// Pattern 객체 생성
Pattern p = Pattern.compile(regex);
System.out.println("Strings with Latin characters: ");
for(int i=0; i<5;i++) {
// Matcher 객체 생성
Matcher m = p.matcher(input[i]);
if(m.matches()) {
System.out.println(m.group());
}
}
}
}실행 결과
Enter 5 input strings: hello how are you This is SAMPLE text 123 465 TEST DATA #$% &# *# Strings with Latin characters: This is SAMPLE text TEST DATA
모두 소문자로 이루어진 "hello how are you", 숫자만 있는 "123 465", 특수문자만 있는 "#$% &# *#"는 제외되고, 대문자를 하나 이상 포함한 "This is SAMPLE text"와 "TEST DATA"만 출력된 것을 확인할 수 있습니다.
함께 알아두면 좋은 POSIX 문자 클래스
\p{Lu}: 대문자(A~Z)\p{Ll}: 소문자(a~z)\p{Alpha}: 알파벳 전체(대소문자)\p{Digit}: 숫자(0~9)\p{Alnum}: 알파벳과 숫자
이처럼 \p{Lu}는 별도의 범위 지정([A-Z]) 없이도 대문자를 간결하고 가독성 있게 표현할 수 있어, 정규식 코드의 유지보수성을 높이는 데 유용합니다.