सबएक्सप्रेशन/मेटाकैरेक्टर “re?” पूर्ववर्ती एक्सप्रेशन की 0 या 1 घटना से मिलान करता है।
उदाहरण 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "Wel?";
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);
}
}
आउटपुट
मिलान की संख्या: 1
उदाहरण 2
निम्नलिखित Java प्रोग्राम उपयोगकर्ता से एक स्ट्रिंग स्वीकार करता है, जांचता है कि क्या इसमें वर्णमाला (दोनों केस) हैं, यह अंक भी स्वीकार करता है।
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 = "[a-zA-Z][0-9]?";
Scanner sc = new Scanner(System.in);
System.out.println("एक इनपुट स्ट्रिंग दर्ज करें: ");
String input = sc.nextLine();
// Pattern ऑब्जेक्ट बनाना
Pattern p = Pattern.compile(regex);
// Matcher ऑब्जेक्ट बनाना
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("मिलान हुआ");
} else {
System.out.println("मिलान नहीं हुआ");
}
}
}
आउटपुट 1
एक इनपुट स्ट्रिंग दर्ज करें: sample text मिलान हुआ
आउटपुट 2
एक इनपुट स्ट्रिंग दर्ज करें: sample text 34 56 मिलान हुआ
आउटपुट 3
एक इनपुट स्ट्रिंग दर्ज करें: 32 89 45 63 मिलान नहीं हुआ