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

หาตำแหน่งและความยาวของการจับคู่ใน Java Regex

คลาส java.util.regex.Matcher มีเมธอดสำหรับหาตำแหน่งและความยาวของการจับคู่:

  • start() - คืนตำแหน่งเริ่มต้นของการจับคู่ (0-based index)
  • end() - คืนตำแหน่ง หลัง ตัวอักษรสุดท้ายของการจับคู่
  • ความยาว = end() - start()

ตัวอย่าง: หาตำแหน่งและความยาวของตัวเลข

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

public class MatcherExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        String regex = "\\d+";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        int start = 0, len = -1;
        
        while (matcher.find()) {
            start = matcher.start();
            len = matcher.end() - start;
        }
        
        System.out.println("Position of the match: " + start);
        System.out.println("Length of the match: " + len);
    }
}

ผลลัพธ์

Enter input text: sample data with digits 12345
Position of the match: 24
Length of the match: 5

อธิบาย

  • ข้อความ "sample data with digits 12345" มีความยาว 24 ตัวอักษรก่อน "12345"
  • start() คืน 24 (index ของ '1')
  • end() คืน 29 (index หลัง '5')
  • ความยาว = 29 - 24 = 5

เมธอดเพิ่มเติมสำหรับกลุ่ม (Groups)

  • start(int group) - ตำแหน่งเริ่มต้นของกลุ่มที่ระบุ
  • end(int group) - ตำแหน่งสิ้นสุดของกลุ่มที่ระบุ
  • group(int group) - ข้อความของกลุ่มที่ระบุ

การใช้งานจริง

เหมาะสำหรับ: ไฮไลท์ข้อความ, แทนที่เฉพาะตำแหน่ง, วิเคราะห์โครงสร้างข้อความ