Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Java

Java में रेगुलर एक्सप्रेशन (re) सब-एक्सप्रेशन


सबएक्सप्रेशन/मेटाकैरेक्टर “( )” रेगुलर एक्सप्रेशन को ग्रुप करता है और मिलान किए गए टेक्स्ट को याद रखता है।

उदाहरण 1

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class Example { 
    public static void main( String args[] ) { 
        String input = "Hello how are you welcome to Tutorialspoint"; 
        String regex = "H(ell|ow)"; 
        // रेगुलर एक्सप्रेशन संकलित करना 
        Pattern pattern = Pattern.compile(regex); 
        // Matcher ऑब्जेक्ट प्राप्त करना 
        Matcher matcher = pattern.matcher(input); 
        if(matcher.find()) { 
            System.out.println("मिलान मिला"); 
        } else { 
            System.out.println("मिलान नहीं मिला"); 
        } 
    } 
}

आउटपुट

मिलान मिला

उदाहरण 2

निम्नलिखित उदाहरण में, हम अंकों वाले वाक्य से मिलान करने का प्रयास कर रहे हैं -

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class PatternExample { 
    public static void main(String[] args) { 
        System.out.println("इनपुट स्ट्रिंग दर्ज करें: "); 
        Scanner sc = new Scanner(System.in); 
        String input = sc.nextLine(); 
        // ग्रुप का उपयोग करके रेगुलर एक्सप्रेशन 
        String regex = "(?:.*)(\\d+)(.*)"; 
        // पैटर्न ऑब्जेक्ट बनाना 
        Pattern pattern = Pattern.compile(regex); 
        // Matcher ऑब्जेक्ट बनाना 
        Matcher matcher = pattern.matcher(input); 
        boolean bool = matcher.matches(); 
        if(bool) { 
            System.out.println("मिलान मिला"); 
        } else { 
            System.out.println("मिलान नहीं मिला"); 
        } 
    } 
}

आउटपुट

इनपुट स्ट्रिंग दर्ज करें: This is a 5363 test string मिलान मिला

  1. - Java में रेगुलर एक्सप्रेशन \D मेटाकैरेक्टर

    सबएक्सप्रेशन/मेटाकैरेक्टर “\D” नॉन-डिजिट से मिलान करता है। उदाहरण 1 import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = \\D; String input = This is sample text 12 2

  1. - Java में रेगुलर एक्सप्रेशन \d कंस्ट्रक्ट

    सबएक्सप्रेशन/मेटाकैरेक्टर “\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

  1. - Java में रेगुलर एक्सप्रेशन \S मेटाकैरेक्टर

    सबएक्सप्रेशन/मेटाकैरेक्टर “\S” नॉन-व्हाइटस्पेस कैरेक्टर से मिलान करता है। उदाहरण 1 import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = \\S; String input = Hello how