Java에서 정규식(Regular Expression)을 활용하면 문자열에서 특정 문자를 손쉽게 필터링하거나 제거할 수 있습니다. 이 글에서는 정규식의 문자 클래스와 부정(negation) 기능을 이용해 문자열에서 자음만 골라내고 삭제하는 방법을 소개합니다.
문자 클래스와 부정(^) 연산자
대괄호로 표현되는 단순 문자 클래스 [ ]는 그 안에 명시된 모든 문자와 일치(match)합니다. 예를 들어 다음과 같이 작성할 수 있습니다.
"[abc]"
여기에 메타 문자 ^를 문자 클래스 내부 맨 앞에 두면 부정(negation)의 의미가 됩니다. 즉, 아래 표현식은 문자 b를 제외한 모든 문자(공백 및 특수 문자 포함)와 일치합니다.
"[^b]"
같은 원리로, 다음 표현식은 입력 문자열에서 모음(a, e, i, o, u, y)과 숫자, 비단어 문자(\W)를 제외한 나머지, 즉 모든 자음과 일치합니다.
"([^aeiouyAEIOUY0-9\\W]+)"
이렇게 매칭된 자음들을 String 클래스의 replaceAll() 메서드를 사용해 빈 문자열 ""로 치환하면, 결과적으로 문자열에서 자음이 제거됩니다.
예제 1: replaceAll() 사용
public class RemovingConstants {
public static void main( String args[] ) {
String input = "Hi welc#ome to t$utori$alspoint";
String regex = "([^aeiouAEIOU0-9\\W]+)";
String result = input.replaceAll(regex, "");
System.out.println("Result: "+result);
}
}실행 결과
Result: i e#oe o $uoi$aoi
위 코드는 입력 문자열에서 모음과 숫자, 특수 문자(#, $ 등)를 남기고 자음만 제거한 결과를 출력합니다.
예제 2: Pattern과 Matcher 사용
java.util.regex 패키지의 Pattern과 Matcher 클래스를 사용하면 더 세밀하게 정규식 매칭을 제어할 수 있습니다. Matcher의 appendReplacement()와 appendTail() 메서드를 활용해 매칭된 자음을 하나씩 치환하는 방식입니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingConsonants {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "([^aeiouyAEIOUY0-9\\W])";
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// 컴파일된 패턴을 문자열에 적용
Matcher matcher = pattern.matcher(input);
// 빈 StringBuffer 생성
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString() );
}
}실행 결과
Enter input string: # Hello how are you welcome to Tutorialspoint # Result: # eo o ae you eoe o uoiaoi #
정리
간단한 치환이 필요하다면 replaceAll() 한 줄로 충분하지만, 매칭 과정을 단계별로 제어해야 하는 경우에는 Pattern과 Matcher를 조합하는 방식이 유용합니다. 두 방법 모두 부정 문자 클래스 [^...]를 활용한다는 점에서 동일한 원리를 공유하므로, 상황에 맞게 선택해 사용하시면 됩니다.