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

วิธาจับคู่คำเฉพาะในสตริงด้วย Pattern class ใน Java


Meta character \b ใน Java regular expressions จับคู่ word boundaries ดังนั้น เพื่อค้นหาคำเฉพาะจากข้อความอินพุตที่กำหนด ให้ระบุคำที่ต้องการภายใน word boundaries ใน regular expressions ดังนี้:

"\\brequired word\\b"

ตัวอย่างที่ 1: ค้นหาคำว่า "hello"

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

public class MachingWordExample1 {
    public static void main(String args[]) {
        // อ่านค่าสตริง
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string");
        String input = sc.next();
        
        // Regular expression เพื่อหาคำว่า hello
        String regex = "\\bhello\\b";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

Output

Enter input string hello welcome to Tutorialspoint
Match found

ตัวอย่างที่ 2: ค้นหาคำว่า "second" ในข้อความหลายบรรทัด

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";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

Output

Match found