Lớp ký tự POSIX \p{Lower} khớp với các ký tự chữ cái thường từ a đến z.
Ví dụ 1: Kiểm tra chuỗi chỉ chứa chữ thường
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PosixLowerExample {
public static void main(String args[]) {
// Biểu thức chính quy khớp toàn bộ chuỗi chỉ chứa chữ thường
String regex = "^\\p{Lower}+$";
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("Các chuỗi chỉ chứa chữ thường:");
for (int i = 0; i < 5; i++) {
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
Kết quả
Nhập 5 chuỗi: Raju RAMU rahman radha SUnDar Các chuỗi chỉ chứa chữ thường: rahman radha
Ví dụ 2: Đếm số ký tự thường trong chuỗi
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập một chuỗi:");
String input = sc.nextLine();
// Biểu thức khớp mỗi ký tự thường
String regex = "\\p{Lower}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ký tự thường trong chuỗi: " + count);
}
}
Kết quả 1
Nhập một chuỗi: Hello How Are You Số ký tự thường trong chuỗi: 10
Kết quả 2
Nhập một chuỗi: WELCOME TO TUTORIALSPOINT Số ký tự thường trong chuỗi: 0