Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมตาอักขระ \b ในนิพจน์ปกติ Java

ซับนิพจน์/เมตาอักขระ “\b” จับคู่ขอบเขตคำ (word boundaries) เมื่ออยู่นอกวงเล็บ จับคู่แบ็กสเปซ (0x08) เมื่ออยู่ในวงเล็บ

ตัวอย่างที่ 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("Enter a string: "); 
        String input = sc.nextLine(); 
        Pattern p = Pattern.compile(regex); 
        Matcher m = p.matcher(input); 
        int count = 0; 
        while(m.find()) { 
            count++; 
        } 
        System.out.println("Number of matches: " + count); 
    } 
}

ผลลัพธ์

Enter a string: A sentence doesn't end with because because, because is a conjunction 
Number of matches: 3

ตัวอย่างที่ 2

ตัวอย่าง Java ต่อไปนี้อ่านค่าสตริงจากผู้ใช้และพิมพ์จำนวนขอบเขตคำ

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("Enter input string: "); 
        Scanner sc = new Scanner(System.in); 
        String input = sc.nextLine(); 
        String regex = "\\b"; 
        // คอมไพล์นิพจน์ปกติ 
        Pattern pattern = Pattern.compile(regex); 
        // ดึงออบเจ็กต์ matcher 
        Matcher matcher = pattern.matcher(input); 
        int count = 0; 
        while(matcher.find()) { 
            count++; 
        } 
        System.out.println(count); 
    } 
}

ผลลัพธ์

Enter input string: Hello how are you welcome to Tutorialspoint 
14