Khái niệm
\p{javaWhitespace} khớp ký tự whitespace theo định nghĩa Java (Character.isWhitespace(c)). Bao gồm: space, tab, newline, form feed, v.v.
Ví dụ 1: Đếm whitespace
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập chuỗi: ");
String input = sc.nextLine();
String regex = "[\\p{javaWhitespace}]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ký tự whitespace: " + count);
}
}
Nhập chuỗi: hello welcome to tutorialspoint
Số ký tự whitespace: 3
Ví dụ 2: Chuỗi chỉ chứa whitespace
String regex = "^\\p{javaWhitespace}+$";
// Input: Raju RAMU rahman radha SUnDar*
// Khớp: (không có dòng nào chỉ toàn whitespace)
Lưu ý: Output ví dụ gốc có vẻ nhầm lẫn với \p{javaUpperCase}.
So sánh \p{javaWhitespace} vs \s
| Đặc điểm | \p{javaWhitespace} | \s |
|---|---|---|
| Định nghĩa | Character.isWhitespace() | Unicode White_Space property |
| Bao gồm | Space, \t, \n, \r, \f, \v, ... | Tương tự nhưng có thể khác ở một số char |
| Performance | Chậm hơn (method call) | Nhanh hơn (built-in) |
Khi nào dùng
- Cần chính xác theo Java spec:
\p{javaWhitespace} - Regex hiệu năng cao, Unicode standard:
\\s