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

Matcher replaceAll() Method ใน Java พร้อมตัวอย่าง


คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern

เมธอด replaceAll() ของคลาส (Matcher) นี้รับค่าสตริง แทนที่ subsequences ที่จับคู่ได้ทั้งหมดในอินพุตด้วยค่าสตริงที่กำหนด และคืนค่าผลลัพธ์

ตัวอย่างที่ 1: แทนที่อักขระพิเศษทั้งหมดด้วย !

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceAllExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        String regex = "[#%&*]";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        
        // ดึง Pattern ที่ใช้
        System.out.println("The are " + count + " special characters [# % & *] in the given text");
        
        // แทนที่อักขระพิเศษทั้งหมด [# % & *] ด้วย !
        String result = matcher.replaceAll("!");
        System.out.println("Replaced all special characters [# % & *] with !: \n" + result);
    }
}

Output

Enter input text: Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !: Hello! How ! are! you !! welcome to T!utorials!point

ตัวอย่างที่ 2: แทนที่ whitespace หลายๆ ตัวด้วยช่องว่างเดียว

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceAllExample {
    public static void main(String args[]) {
        // อ่าน String จากผู้ใช้
        System.out.println("Enter a String");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        // Regular expression to match spaces (one or more)
        String regex = "\\s+";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // แทนที่ช่องว่างทั้งหมดด้วยช่องว่างเดียว
        String result = matcher.replaceAll(" ");
        System.out.print("Text after removing unwanted spaces: \n" + result);
    }
}

Output

Enter a String hello this is a sample text with irregular spaces
Text after removing unwanted spaces: hello this is a sample text with irregular spaces