java.util.regex पैकेज का Pattern क्लास एक रेगुलर एक्सप्रेशन का कंपाइल्ड प्रतिनिधित्व है।
इस क्लास का toString() मेथड उस रेगुलर एक्सप्रेशन का स्ट्रिंग प्रतिनिधित्व लौटाता है जिसका उपयोग वर्तमान Pattern को कंपाइल करने के लिए किया गया था।
उदाहरण 1
import java.util.Scanner;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// स्ट्रिंग मान पढ़ना
Scanner sc = new Scanner(System.in);
System.out.println("इनपुट स्ट्रिंग दर्ज करें");
String input = sc.nextLine();
// अंक खोजने के लिए रेगुलर एक्सप्रेशन
String regex = "(\\d)";
// रेगुलर एक्सप्रेशन कंपाइल करना
Pattern pattern = Pattern.compile(regex);
// रेगुलर एक्सप्रेशन प्रिंट करना
System.out.println("कंपाइल्ड रेगुलर एक्सप्रेशन: " + pattern.toString());
// यह सत्यापित करना कि मिलान हुआ या नहीं
if(pattern.matcher(input).find())
System.out.println("दिया गया स्ट्रिंग अंक रखता है");
else
System.out.println("दिया गया स्ट्रिंग अंक नहीं रखता");
}
}
आउटपुट
इनपुट स्ट्रिंग दर्ज करें This 7est contain5 di9its in place of certain charac7er5 कंपाइल्ड रेगुलर एक्सप्रेशन: (\d) दिया गया स्ट्रिंग अंक रखता है
उदाहरण 2
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "Tutorialspoint$";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(input);
int count = 0;
if(match.find())
System.out.println("मिलान मिला");
else
System.out.println("मिलान नहीं मिला");
System.out.println("रेगुलर एक्सप्रेशन: " + pattern.toString());
}
}
आउटपुट
मिलान मिला रेगुलर एक्सप्रेशन: Tutorialspoint$