Posix 문자 클래스 \p{ASCII} ASCII 문자와 일치하고 메타 문자 ^는 부정으로 작동합니다.
즉, 다음 표현식은 ASCII가 아닌 모든 문자와 일치합니다.
"[^\\p{ASCII}]" String 클래스의 replaceAll() 메서드는 정규식과 교체 문자열을 받아들이고 현재 문자열(주어진 패턴과 일치)의 문자를 지정된 교체 문자열로 바꿉니다.
따라서 replaceAll() 메서드를 사용하여 일치하는 문자를 빈 문자열 "로 대체하여 제거할 수 있습니다.
예시 1
import java.util.Scanner;
public class Exp {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
String regex = "[^\\p{ASCII}]";
System.out.println("Enter input data:");
String input = sc.nextLine();
String result = input.replaceAll(regex, "");
System.out.println("Result: "+result);
}
} 출력
Enter input data: whÿ do we fall Result: wh do we fall
예시 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "[^\\p{ASCII}]";
//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: whÿ do we fall Result: wh do we fall