सबएक्सप्रेशन/मेटाकैरेक्टर “\d” अंकों से मिलान करता है।
उदाहरण 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\d 24";
String input = "This is sample text 12 24 56 89 24";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("मिलान की संख्या: " + count);
}
}
आउटपुट
मिलान की संख्या: 2
उदाहरण 2
निम्नलिखित Java प्रोग्राम उपयोगकर्ता से 10-अंकीय संख्या पढ़ता है।
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
String regex = "\\d{10}";
Scanner sc = new Scanner(System.in);
System.out.println("अपना फोन नंबर दर्ज करें (10 अंक): ");
String input = sc.nextLine();
// Pattern ऑब्जेक्ट बनाना
Pattern p = Pattern.compile(regex);
// Matcher ऑब्जेक्ट बनाना
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("OK");
} else {
System.out.println("गलत इनपुट");
}
}
}
आउटपुट 1
अपना फोन नंबर दर्ज करें (10 अंक): 9848022338 OK
आउटपुट 2
अपना फोन नंबर दर्ज करें (10 अंक): 545 गलत इनपुट