Java नियमित अभिव्यक्तियां 3 लॉजिकल ऑपरेटर्स का समर्थन करती हैं:
- XY: X के बाद Y
- X|Y: X या Y
- (X): कैप्चरिंग समूह।
XY: X के बाद Y
यह केवल दो लगातार एकल वर्णों से मेल खाता है।
उदाहरण
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "am";
// पैटर्न ऑब्जेक्ट बनाना
Pattern pattern = Pattern.compile(regex);
// स्ट्रिंग में संकलित पैटर्न का मिलान
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
आउटपुट 1
Enter input text: sample text Match occurred
आउटपुट 2
Enter input text: hello how are you Match not occurred
X|Y
यह "|" से घिरे दो अभिव्यक्तियों/वर्णों में से किसी एक से मेल खाता है।
उदाहरण
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "Hello|welcome";
String input = "Hello how are you welcome to Tutorialspoint";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of matches: " + count);
}
}
आउटपुट
Number of matches: 2
(X): कैप्चरिंग समूह
एक कैप्चरिंग समूह आपको कई वर्णों को एक इकाई के रूप में मानने की अनुमति देता है। आपको बस इन वर्णों को कोष्ठक के एक सेट के अंदर रखना होगा।
उदाहरण
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CapturingGroups {
public static void main(String args[]) {
System.out.println("Enter input text");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "(.*)(\\d+)(.*)";
// पैटर्न ऑब्जेक्ट बनाएं
Pattern pattern = Pattern.compile(regex);
// अब मिलानकर्ता ऑब्जेक्ट बनाएं
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Found value: " + matcher.group(0));
System.out.println("Found value: " + matcher.group(1));
System.out.println("Found value: " + matcher.group(2));
System.out.println("Found value: " + matcher.group(3));
} else {
System.out.println("NO MATCH");
}
}
}
आउटपुट
Enter input text: sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: 4 Found value: (digits) in middle