Pattern क्लास का compile मेथड दो पैरामीटर्स स्वीकार करता है −
- रेगुलर एक्सप्रेशन को दर्शाने वाला एक स्ट्रिंग मान।
- Pattern क्लास के एक फील्ड का एक इंटीजर मान।
Pattern क्लास का CASE_INSENSITIVE फील्ड कैरेक्टर्स को केस की परवाह किए बिना मिलान करता है। इसलिए, यदि आप इसे अपने रेगुलर एक्सप्रेशन के साथ compile() मेथड में फ्लैग वैल्यू के रूप में पास करते हैं, तो दोनों केस के कैरेक्टर्स मिलान किए जाएंगे।
उदाहरण 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input data: ");
String input = sc.nextLine();
// आवश्यक कैरेक्टर खोजने के लिए रेगुलर एक्सप्रेशन
String regex = "test";
// रेगुलर एक्सप्रेशन को कंपाइल करना
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
// Matcher ऑब्जेक्ट प्राप्त करना
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
count++;
}
System.out.println("Number of occurrences: "+count);
}
}आउटपुट
Enter input data: test TEST Test sample data Number of occurrences: 3
उदाहरण 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
}
}आउटपुट
Enter a string value: TRUE Given string is a boolean type