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

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


คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern

เมธอด pattern() ของคลาส (Matcher) นี้ดึงและคืนค่า Pattern (object) ที่ถูกตีความโดย Matcher ปัจจุบัน

ตัวอย่างที่ 1: Validate วันที่ MM/DD/YYYY

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

public class PatternExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your date of birth (MM/DD/YYY)");
        String date = sc.next();
        String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(date);
        
        // Validate วันที่
        if (matcher.matches())
            System.out.println("Date is valid");
        else
            System.out.println("Date is not valid");
        
        // ดึง Pattern ที่ใช้
        Pattern p = matcher.pattern();
        System.out.println("Pattern used to match the given date: \n" + p);
    }
}

Output

Enter your date of birth 01/21/2019
Date is valid
Pattern used to match the given date: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$

ตัวอย่างที่ 2: ตรวจสอบตัวอักษรแรกเป็นตัวเลข

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

public class PatternExample {
    public static void main(String args[]) {
        // อ่าน String จากผู้ใช้
        System.out.println("Enter a String");
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        // Regular expression to match word that starts with a digit
        String regex = "^[0-9].*$";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        Pattern p = matcher.pattern();
        System.out.println("Pattern used to match the given input string: " + p);
        
        // ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
        if (matcher.matches())
            System.out.println("First character is a digit");
        else
            System.out.println("First character is not a digit");
    }
}

Output

Enter a String 2sample
Pattern used to match the given input string: ^[0-9].*$
First character is a digit