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

Giải thích Metaký tự \B trong Java Regular Expressions

Phần biểu thức/metaký tự “\B” khớp với ranh giới không phải từ (non-word boundaries).

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 = "\\Bcause";
        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

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;
        System.out.println("Ranh giới không phải từ: ");
        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
Ranh giới không phải từ: 30