Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Metaký tự \b trong Regular Expression Java

Phần biểu thức/metaký tự “\b” khớp với ranh giới từ (word boundaries) khi ở ngoài ngoặc vuông. Khớp với backspace (0x08) khi ở trong ngoặc vuông.

Ví dụ 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\bbecause\\b";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập một chuỗi: ");
        String input = sc.nextLine();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        int count = 0;
        while (m.find()) {
            count++;
        }
        System.out.println("Số lần khớp: " + count);
    }
}

Kết quả

Nhập một chuỗi: A sentence doesn't end with because because, because is a conjunction
Số lần khớp: 3

Ví dụ 2

Ví dụ Java sau đọc giá trị chuỗi từ người dùng và in số ranh giới từ.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String args[]) {
        System.out.println("Nhập chuỗi đầu vào: ");
        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(count);
    }
}

Kết quả

Nhập chuỗi đầu vào: Hello how are you welcome to Tutorialspoint
14