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

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


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

เมธอด toMatchResult() ของคลาส (Matcher) นี้คืนค่า match state ของ matcher ปัจจุบัน

ตัวอย่างที่ 1: ดู match state ระหว่าง find()

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

public class ToMatchResultExample {
    public static void main(String[] args) {
        String str = "<p>This <b>is</b> an <b>example</b>.</p>";
        // Regular expression to match contents of the bold tags
        String regex = "<b>(\\S+)</b>";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // จับคู่ pattern ที่คอมไพล์แล้วใน String
        System.out.println("State of the matcher: ");
        Matcher matcher = pattern.matcher(str);
        
        while (matcher.find()) {
            System.out.println(matcher.toMatchResult());
            String result = matcher.group(1);
        }
        
        matcher = matcher.reset("<p>this is another <b>line</b>.</p>");
        matcher.find();
        System.out.println("");
        System.out.println("State of the matcher after resetting it: \n" + matcher.toMatchResult());
    }
}

Output

State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,40 lastmatch=<b>is</b>]
java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,40 lastmatch=<b>example</b>]
State of the matcher after resetting it: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,35 lastmatch=<b>line</b>]

ตัวอย่างที่ 2: หา # ในสตริง

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

public class ToMatchResultExample {
    public static void main(String[] args) {
        String regex = "[#]";
        System.out.println("Enter a string: ");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        System.out.println("Match state: ");
        
        // หาจุดจับคู่
        while (matcher.find()) {
            System.out.println(matcher.toMatchResult());
        }
    }
}

Output

Enter a string: #This #is #a #sample #text
Match state: java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]