ซับนิพจน์/เมตาอักขระ “re{ n}” จับคู่จำนวน n ครั้งอย่างแน่นอนของนิพจน์ก่อนหน้า
ตัวอย่างที่ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "to{1}";
String input = "Welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: " + count);
}
}ผลลัพธ์
Number of matches: 2
ตัวอย่างที่ 2
โปรแกรม Java ต่อไปนี้อ่านค่าอายุจากผู้ใช้ อนุญาตเฉพาะตัวเลข 2 หลัก
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\d{2}";
System.out.println("Enter your age:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.matches()) {
System.out.println("Age value accepted");
} else {
System.out.println("Age value not accepted");
}
}
}ผลลัพธ์ที่ 1
Enter your age: 25 Age value accepted
ผลลัพธ์ที่ 2
Enter your age: 2252 Age value not accepted
ผลลัพธ์ที่ 3
Enter your age: twenty Age value not accepted