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

วิธีจับคู่ขอบเขตคำด้วย Java RegEx

คุณสามารถจับคู่ขอบเขตคำได้โดยใช้เมตาอักขระ “\\b”

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

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 a 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("Number of word boundaries: " + count); 
    } 
}

ผลลัพธ์

Enter a String this is a sample text 
Number of word boundaries: 10

ตัวอย่างที่ 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("Enter sample text: "); 
        String data = sc.nextLine(); 
        String regex = "\\b[a-zA-Z]"; 
        // สร้างออบเจ็กต์ pattern 
        Pattern pattern = Pattern.compile(regex); 
        // สร้างออบเจ็กต์ Matcher 
        Matcher matcher = pattern.matcher(data); 
        System.out.println("First letter of each word from the given string: "); 
        while(matcher.find()) { 
            System.out.print(matcher.group() + " "); 
        } 
    } 
}

ผลลัพธ์

Enter sample text: National Intelligence Agency Research & Analysis Wing 
First letter of each word from the given string: N I A R A W