Ký tự meta "\\s" khớp với khoảng trắng và + chỉ ra việc xuất hiện một hoặc nhiều lần. Do đó, biểu thức chính quy \\s+ khớp với tất cả các ký tự khoảng trắng ( đơn hoặc nhiều). Để thay thế nhiều khoảng trắng bằng một khoảng trắng đơn, khớp chuỗi đầu vào với biểu thức chính quy trên và thay thế kết quả bằng một khoảng trắng " ".
Ví dụ 1: Sử dụng Matcher.replaceAll()
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
System.out.println("Nhập một chuỗi:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\s+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// Thay thế tất cả khoảng trắng bằng một khoảng trắng đơn
String result = matcher.replaceAll(" ");
System.out.print("Văn bản sau khi loại bỏ khoảng trắng thừa: \n" + result);
}
}
Kết quả
Nhập một chuỗi: hello this is a sample text with irregular spaces Văn bản sau khi loại bỏ khoảng trắng thừa: hello this is a sample text with irregular spaces
Ví dụ 2: Sử dụng String.replaceAll()
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
System.out.println("Nhập một chuỗi:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Biểu thức khớp khoảng trắng (một hoặc nhiều)
String regex = "\\s+";
// Thay thế mẫu bằng một khoảng trắng đơn
String result = input.replaceAll(regex, " ");
System.out.print("Văn bản sau khi loại bỏ khoảng trắng thừa: \n" + result);
}
}
Kết quả
Nhập một chuỗi: hello this is a sample text with irregular spaces Văn bản sau khi loại bỏ khoảng trắng thừa: hello this is a sample text with irregular spaces