Possessive Quantifier [X?+] จับคู่ X ที่ปรากฏ 1 ครั้ง หรือ ไม่ปรากฏเลย (0 หรือ 1 ครั้ง) และเป็น possessive - หมายถึงเมื่อจับคู่ได้แล้วจะไม่ย้อนกลับ (backtrack)
ตัวอย่าง
package com.tutorialspoint;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PossesiveQuantifierDemo {
private static final String REGEX = "T?+";
private static final String INPUT = "abcdTatW";
public static void main(String[] args) {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(INPUT);
while (matcher.find()) {
System.out.println("Match String start(): " + matcher.start());
}
}
}
ผลลัพธ์
Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8
อธิบาย
- Regex
T?+= possessive quantifier สำหรับ 'T' 0 หรือ 1 ครั้ง - Input "abcdTatW" มีความยาว 8 ตัวอักษร (index 0-7) + ตำแหน่งสิ้นสุด 8
- Possessive ?+ จับคู่สตริงว่างที่ทุกตำแหน่ง (0-8) และ 'T' ที่ index 4
- แตกต่างจาก
T?(greedy) และT??(reluctant) ที่อาจมีพฤติกรรม backtrack แตกต่าง
Possessive Quantifiers ทั้งหมด
| Quantifier | ความหมาย |
|---|---|
X*+ | 0 หรือมากกว่า (possessive) |
X?+ | 0 หรือ 1 (possessive) |
X++ | 1 หรือมากกว่า (possessive) |
X{n}+ | n ครั้งพอดี (possessive) |
X{n,m}+ | n ถึง m ครั้ง (possessive) |
ความแตกต่าง Greedy vs Reluctant vs Possessive
- Greedy (X*): จับคู่มากที่สุด แล้ว backtrack ถ้าจำเป็น
- Reluctant (X*?): จับคู่น้อยที่สุด แล้วขยายถ้าจำเป็น
- Possessive (X*+): จับคู่มากที่สุด ไม่ backtrack เลย
Possessive เร็วกว่าเมื่อไม่มีการจับคู่ (fail fast) แต่อาจพลาดกรณีที่ต้อง backtrack