Quantifiers ใช้ระบุจำนวนครั้งที่รูปแบบต้องจับคู่ ตารางด้านล่างแสดง quantifiers ที่ Java รองรับ:
| Quantifier | ความหมาย | ตัวอย่าง |
re* | 0 หรือมากกว่า | [0-9]*: 0 หรือหลายหลัก |
re? | 0 หรือ 1 | [0-9]?: 0 หรือ 1 หลัก |
re+ | 1 หรือมากกว่า | [0-9]+: 1 หลักขึ้นไป |
re{n} | n ครั้งพอดี | [0-9]{3}: 3 หลักพอดี |
re{n,} | อย่างน้อย n | [0-9]{3,}: อย่างน้อย 3 หลัก |
re{n,m} | n ถึง m | [0-9]{2,5}: 2-5 หลัก |
ตัวอย่าง: ยืนยันตัวเลข 3-6 หลัก
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "[0-9]{3,6}";
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 input strings: ");
String[] input = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
Pattern p = Pattern.compile(regex);
System.out.println("Matched values:");
for (int i = 0; i < 5; i++) {
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group() + ": accepted");
}
}
}
}
ผลลัพธ์
Enter 5 input strings:
12
154
4587
478365
4578952
Matched values:
154: accepted
4587: accepted
478365: accepted
อธิบาย
- Regex
[0-9]{3,6} รับตัวเลข 3 ถึง 6 หลัก
12 (2 หลัก) - ไม่ผ่าน
154 (3 หลัก) - ผ่าน
4587 (4 หลัก) - ผ่าน
478365 (6 หลัก) - ผ่าน
4578952 (7 หลัก) - ไม่ผ่าน
- ใช้
m.matches() ต้องจับคู่ทั้งสตริง
โหมด Quantifiers ทั้ง 3 แบบ
| โหมด | Syntax | พฤติกรรม |
| Greedy (default) | * + ? {n,m} | จับคู่มากที่สุด แล้ว backtrack |
| Reluctant | *? +? ?? {n,m}? | จับคู่น้อยที่สุด แล้วขยาย |
| Possessive | *+ ++ ?+ {n,m}+ | จับคู่มากที่สุด ไม่ backtrack |