English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java에서 정규 표현식을 사용하여 문자열에서 모음을 제거하는 방법

간단한 문자 클래스 "[]"은 그 안에 있는 모든 지정된 문자를 일치시킵니다. 다음 표현식은 xyz 이외의 문자를 일치시킵니다.

"[xyz]"

또한, 다음 표현식은 주어진 입력 문자열에 있는 모든 모음을 일치시킵니다.

"([^aeiouAEIOU0-9\\W]+)";

그런 다음, 빈 문자열 ""로 일치하는 문자를 대체할 수 있습니다. replaceAll() 메서드를 사용하여 대체합니다.

예제1

public class RemovingVowels {
   public static void main( String args[] ) {
      String input = "Hi welcome to w3codebox";
      String regex = "[aeiouAEIOU]";
      String result = input.replaceAll(regex, "");
      System.out.println("결과: "+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("입력 문자열을 입력하세요: ");
      String input = sc.nextLine();
      String regex = "[aeiouAEIOU]";
      String constants = "";
      System.out.println("입력 문자열: \n"+input);
      //모델 객체를 생성합니다
      Pattern pattern = Pattern.compile(regex);
      //문자열 중의 구성 모델을 일치시킵니다
      Matcher matcher = pattern.matcher(input);
      //빈 문자열 버퍼를 생성합니다
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         constants = constants+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("결과: \n"+ sb.toString()+constants );
   }
}
출력 결과
입력 문자열을 입력하세요:
this is a sample text
입력 문자열:
this is a sample text
결과:
ths s smpl txtiiaaee

좋아할 것 같은 것