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

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


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

เมธอด usePattern() ของคลาส Matcher รับ Pattern object ที่แทน regex pattern ใหม่ และใช้มันเพื่อค้นหาจุดจับคู่

ตัวอย่าง

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

public class UsePatternExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        String regex = "[#%&*]";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        
        // ดึง Pattern ที่ใช้
        System.out.println("The are " + count + " special characters [# % & *] in the given text");
        
        // สร้าง pattern ใหม่สำหรับ 5 ถึง 6 ตัวอักษร
        Pattern newPattern = Pattern.compile("\\A(?=\\w{6,15}\\z)");
        
        // สลับไปใช้ pattern ใหม่
        matcher = matcher.usePattern(newPattern);
        
        if (matcher.find()) {
            System.out.println("Given input contain 6 to 15 characters");
        } else {
            System.out.println("Given input doesn't contain 6 to 15 characters");
        }
    }
}

Output

Enter input text: #*mypassword&
The are 3 special characters [# % & *] in the given text
!!mypassword!
Given input doesn't contain 6 to 15 characters