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

วิธีลบสระออกจากสตริงด้วย Regular Expressions ใน Java


Simple character class "[ ]" จับคู่ตัวอักษรที่ระบุทั้งหมด นิพจน์ต่อไปนี้จับคู่ตัวอักษรยกเว้น xyz:

"[xyz]"

เช่นเดียวกัน นิพจน์ต่อไปนี้จับคู่สระทั้งหมดในสตริงอินพุตที่กำหนด:

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

จากนั้นคุณสามารถลบตัวอักษรที่จับคู่ได้โดยการแทนที่ด้วยสตริงว่าง "" โดยใช้เมธอด replaceAll()

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

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);
    }
}

Output

Result: H wlcm t ttrlspnt

ตัวอย่างที่ 2: ใช้ Pattern และ Matcher

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);
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // จับคู่ pattern ที่คอมไพล์แล้วในสตริง
        Matcher matcher = pattern.matcher(input);
        
        // สร้าง StringBuffer ว่าง
        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);
    }
}

Output

Enter input string: this is a sample text
Input string: this is a sample text
Result: ths s smpl txtiiaaee