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

เมธอด quote() ของ Pattern ใน Java พร้อมตัวอย่าง

แพ็กเกจ java.util.regex ของ Java มีคลาสต่างๆ สำหรับค้นหารูปแบบเฉพาะในลำดับตัวอักษร คลาส Pattern ของแพ็กเกจนี้เป็นการแสดงรูปแบบที่คอมไพล์แล้วของนิพจน์ปกติ เมธอด quote() ของคลาสนี้รับค่าสตริงและส่งคืนสตริงรูปแบบที่จะจับคู่กับสตริงที่กำหนด นั่นคือ จะเพิ่มเมตาอักขระและลำดับการหลบหนี (escape sequences) ให้กับสตริงที่กำหนด แต่ความหมายของสตริงเดิมจะไม่เปลี่ยนแปลง

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

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class QuoteExample { 
    public static void main( String args[] ) { 
        // อ่านค่าสตริง 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter input string"); 
        String input = sc.nextLine(); 
        System.out.print("Enter the string to be searched: "); 
        String regex = Pattern.quote(sc.nextLine()); 
        System.out.println("pattern string: " + regex); 
        // คอมไพล์นิพจน์ปกติ 
        Pattern pattern = Pattern.compile(regex); 
        // ดึงออบเจ็กต์ Matcher 
        Matcher matcher = pattern.matcher(input); 
        if(matcher.find()) { 
            System.out.println("Match found"); 
        } else { 
            System.out.println("Match not found"); 
        } 
    } 
}

ผลลัพธ์

Enter input string This is an example program demonstrating the quote() method 
Enter the string to be searched: the 
pattern string: \Qthe\E 
Match found

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

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class QuoteExample { 
    public static void main( String args[] ) { 
        String regex = "[aeiou]"; 
        String input = "Hello how are you welcome to Tutorialspoint"; 
        Pattern.compile(regex); 
        regex = Pattern.quote(regex); 
        System.out.println("pattern string: " + regex); 
        Pattern pattern = Pattern.compile(regex); 
        Matcher matcher = pattern.matcher(input); 
        if(matcher.find()) { 
            System.out.println("The input string contains vowels"); 
        } else { 
            System.out.println("The input string does not contain vowels"); 
        } 
    } 
}

ผลลัพธ์

pattern string: \Q[aeiou]\E 
The input string contains vowels