Khái niệm
\p{Blank} khớp tất cả tab hoặc khoảng trắng (space, tab).
Ví dụ 1: Đếm ký tự blank
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PrintableCharacters {
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{Blank}]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ký tự blank: " + count);
}
}
Nhập chuỗi: space tab test
Số ký tự blank: 2
Ví dụ 2: Lọc chuỗi chứa blank
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String regex = "^.*\\p{Blank}.*$";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi: ");
String[] input = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
Pattern p = Pattern.compile(regex);
System.out.println("Chuỗi có ký tự blank: ");
for (int i = 0; i < 5; i++) {
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
Nhập 5 chuỗi: sample data hello welcome to tutorialspoint 12345 ab bc cd da
Chuỗi có ký tự blank:
sample data
welcome to tutorialspoint
ab bc cd da
Các POSIX Character Classes phổ biến
| Class | Ý nghĩa | Tương đương |
|---|---|---|
\p{Blank} | Space, tab | [ \t] |
\p{Space} | Whitespace | \\s |
\p{Digit} | Chữ số | \\d |
\p{Alpha} | Chữ cái | [A-Za-z] |
\p{Alnum} | Chữ và số | [A-Za-z0-9] |
\p{Punct} | Dấu câu | [!\"#$%&'()*+,\-./:;<=>?@[\\]^_`{|}~] |
\p{Graph} | In được (không space) | [^\\s] |
\p{Print} | In được (có space) | [\\s\\S] trừ control |
\p{XDigit} | Hex digit | [0-9A-Fa-f] |