Bạn có thể khớp ranh giới từ bằng metaký tự “\\b”.
Ví dụ 1
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();
String regex = "\\b";
// 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);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ranh giới từ: " + count);
}
}
Kết quả
Nhập một chuỗi this is a sample text Số ranh giới từ: 10
Ví dụ 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập văn bản mẫu: ");
String data = sc.nextLine();
String regex = "\\b[a-zA-Z]";
// Tạo đối tượng pattern
Pattern pattern = Pattern.compile(regex);
// Tạo đối tượng Matcher
Matcher matcher = pattern.matcher(data);
System.out.println("Chữ cái đầu của mỗi từ từ chuỗi đã cho: ");
while (matcher.find()) {
System.out.print(matcher.group() + " ");
}
}
}
Kết quả
Nhập văn bản mẫu: National Intelligence Agency Research & Analysis Wing Chữ cái đầu của mỗi từ từ chuỗi đã cho: N I A R A W