Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 정규식을 사용하여 문자열에서 자음을 제거하는 방법은 무엇입니까?

<시간/>

단순 문자 클래스 "[ ] "는 그 안에 지정된 모든 문자와 일치합니다. 메타 캐릭터 ^ 위의 문자 클래스 내에서 부정으로 작동합니다. 즉, 다음 표현식은 b(공백 및 특수 문자 포함)를 제외한 모든 문자와 일치합니다.

"[^b]"

마찬가지로 다음 표현식은 주어진 입력 문자열의 모든 자음과 일치합니다.

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

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

예시 1

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

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])";
      String constants = "";
      //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()) {
         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 #