Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีลบ Non-ASCII Characters จาก String ใน Java

Posix character class \p{ASCII} match ตัวอักษร ASCII และ metacharacter ^ ทำหน้าที่ negation

ดังนั้น regex ต่อไปนี้ match non-ASCII characters ทั้งหมด:

"[^\\p{ASCII}]"

เมธอด replaceAll() ของ String class รับ regex และ replacement string แทนที่ตัวอักษรที่ match ด้วย replacement string ดังนั้นสามารถลบ non-ASCII chars ได้โดยแทนที่ด้วย empty string ""

ตัวอย่าง 1 (ใช้ replaceAll)

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 (ใช้ Matcher.appendReplacement)

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}]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        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