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

Pattern toString() Method ใน Java พร้อมตัวอย่าง


คลาส Pattern ของแพ็กเกจ java.util.regex เป็น compiled representation ของ regular expression

เมธอด toString() ของคลาสนี้คืนค่า string representation ของ regular expression ที่ใช้คอมไพล์ Pattern ปัจจุบัน

ตัวอย่างที่ 1: แสดง regex ที่ compile

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

public class Example {
    public static void main(String args[]) {
        // อ่านค่าสตริง
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string");
        String input = sc.nextLine();
        
        // Regular expression to find digits
        String regex = "(\\d)";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // พิมพ์ regular expression
        System.out.println("Compiled regular expression: " + pattern.toString());
        
        // ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
        if (pattern.matcher(input).find())
            System.out.println("Given String contains digits");
        else
            System.out.println("Given String does not contain digits");
    }
}

Output

Enter input string This 7est contain5 di9its in place of certain charac7er5
Compiled regular expression: (\d)
Given String contains digits

ตัวอย่างที่ 2: regex Tutorialspoint$

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

public class Example {
    public static void main(String args[]) {
        String regex = "Tutorialspoint$";
        String input = "Hi how are you welcome to Tutorialspoint";
        Pattern pattern = Pattern.compile(regex);
        Matcher match = pattern.matcher(input);
        int count = 0;
        if (match.find())
            System.out.println("Match found");
        else
            System.out.println("Match not found");
        System.out.println("regular expression: " + pattern.toString());
    }
}

Output

Match found
regular expression: Tutorialspoint$