Phần biểu thức/metaký tự “\s” khớp với khoảng trắng (white space equivalent).
Ví dụ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "\\s";
String input = "Hello how are you welcome to Tutorialspoint !";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("Số lần khớp: " + count);
}
}
Kết quả
Số lần khớp: 7
Ví dụ 2
Ví dụ sau đọc một chuỗi và xóa tất cả khoảng trắng thừa giữa các từ.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// Đọc chuỗi từ người dùng
System.out.println("Nhập một chuỗi");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Biểu thức chính quy khớp khoảng trắng (một hoặc nhiều)
String regex = "\\s+";
// Biên dịch biểu thức chính quy
Pattern pattern = Pattern.compile(regex);
// Lấy đối tượng matcher
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 xóa 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 xóa khoảng trắng thừa: hello this is a sample text with irregular spaces