정규식(Regular Expression)에서 문자 클래스 [ ]는 대괄호 안에 지정된 문자 중 하나와 일치합니다. 예를 들어 다음 표현식은 x, y, z 중 하나의 문자와 일치합니다.
"[xyz]"
마찬가지로 다음 표현식은 영문 모음 a, e, i, o, u(대소문자 모두)와 일치합니다.
"[aeiouAEIOU]"
이렇게 매칭된 문자를 replaceAll() 메서드로 빈 문자열 ""로 치환하면, 문자열에서 모음을 손쉽게 제거할 수 있습니다.
예제 1: replaceAll() 메서드 활용
public class RemovingVowels {
public static void main( String args[] ) {
String input = "Hi welcome to tutorialspoint";
String regex = "[aeiouAEIOU]";
String result = input.replaceAll(regex, "");
System.out.println("Result: "+result);
}
}실행 결과
Result: H wlcm t ttrlspnt
예제 2: Pattern과 Matcher 클래스 활용
java.util.regex 패키지의 Pattern과 Matcher 클래스를 사용하면 정규식 매칭 과정을 더 세밀하게 제어할 수 있습니다. 아래 예제는 사용자로부터 문자열을 입력받아 모음을 제거한 결과와 함께, 제거된 모음들도 별도로 출력합니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "[aeiouAEIOU]";
String vowels = "";
System.out.println("Input string: \n"+input);
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// 컴파일된 패턴을 문자열에 적용
Matcher matcher = pattern.matcher(input);
// 결과를 담을 StringBuffer 생성
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
vowels = vowels+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+vowels );
}
}실행 결과
Enter input string: this is a sample text Input string: this is a sample text Result: ths s smpl txtiiaaee