Metacharacter \b trong biểu thức chính quy Java khớp với ranh giới từ. Do đó, để tìm một từ cụ thể từ văn bản đầu vào, hãy chỉ định từ yêu cầu trong ranh giới từ trong biểu thức chính quy như sau:
"\\brequired word\\b"
Ví dụ 1: Tìm từ "hello"
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MachingWordExample1 {
public static void main(String args[]) {
// Đọc giá trị chuỗi
Scanner sc = new Scanner(System.in);
System.out.println("Nhập chuỗi đầu vào");
String input = sc.next();
// Biểu thức chính quy để tìm từ "hello"
String regex = "\\bhello\\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);
if (matcher.find()) {
System.out.println("Tìm thấy khớp");
} else {
System.out.println("Không tìm thấy khớp");
}
}
}
Kết quả
Nhập chuỗi đầu vào hello welcome to Tutorialspoint Tìm thấy khớp
Ví dụ 2: Tìm từ "second" trong văn bản nhiều dòng
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample2 {
public static void main(String args[]) {
String input = "This is sample text \n" + "This is second line " + "This is third line";
String regex = "\\bsecond\\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);
if (matcher.find()) {
System.out.println("Tìm thấy khớp");
} else {
System.out.println("Không tìm thấy khớp");
}
}
}
Kết quả
Tìm thấy khớp