Phương thức replaceAll()
Sau khi compile regex và có Matcher, dùng matcher.replaceAll(replacement) để thay thế tất cả phần khớp bằng chuỗi thay thế.
Ví dụ 1: Thay tab thành khoảng trắng đơn
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập văn bản: ");
String input = sc.nextLine();
String regex = "\\t+"; // một hoặc nhiều tab
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số lần khớp: " + count);
String result = matcher.replaceAll(" ");
System.out.println("Kết quả: " + result);
}
}
Nhập văn bản: sample text with tab spaces
Số lần khớp: 4
Kết quả: sample text with tab spaces
Ví dụ 2: Thay thế khớp đầu tiên - replaceFirst()
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập văn bản: ");
String input = sc.nextLine();
String regex = "\\d"; // chữ số
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số lần khớp: " + count);
String result = matcher.replaceFirst("#");
System.out.println("Kết quả: " + result);
}
}
Nhập văn bản: test data 1 2 3
Số lần khớp: 3
Kết quả: test data # 2 3
Lưu ý quan trọng
replaceAll()vàreplaceFirst()gọi trên Matcher, không phải String.- Sau khi gọi
find()trong vòng lặp, state của Matcher thay đổi. Nên reset hoặc tạo Matcher mới trước khi replace. String.replaceAll(regex, repl)là phương thức tiện ích nội bộ tạo Pattern/Matcher tự động.