단순 문자 클래스 "[ ]"는 그 안에 있는 모든 지정된 문자와 일치합니다. 다음 표현식은 xyz를 제외한 문자와 일치합니다.
"[xyz]"
마찬가지로 다음 표현식은 주어진 입력 문자열의 모든 모음과 일치합니다.
"([^aeiouAEIOU0-9\\W]+)";
그런 다음 replaceAll() 메서드를 사용하여 일치하는 문자를 빈 문자열 ""로 교체하여 제거할 수 있습니다.
예시 1
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
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 constants = "";
System.out.println("Input string: \n"+input);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+constants );
}
} 출력
Enter input string: this is a sample text Input string: this is a sample text Result: ths s smpl txtiiaaee