सबएक्सप्रेशन/मेटाकैरेक्टर “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("मिलान की संख्या: " + count);
}
}
आउटपुट
मिलान की संख्या: 2
उदाहरण 2
निम्नलिखित Java प्रोग्राम उपयोगकर्ता से उम्र मान पढ़ता है यह केवल दो अंकों की संख्या की अनुमति देता है।
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("अपनी उम्र दर्ज करें:");
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("उम्र मान स्वीकार किया गया");
} else {
System.out.println("उम्र मान स्वीकार नहीं किया गया");
}
}
}
आउटपुट 1
अपनी उम्र दर्ज करें: 25 उम्र मान स्वीकार किया गया
आउटपुट 2
अपनी उम्र दर्ज करें: 2252 उम्र मान स्वीकार नहीं किया गया
आउटपुट 3
अपनी उम्र दर्ज करें: twenty उम्र मान स्वीकार नहीं किया गया