কম্পিউটার টিউটোরিয়াল

জাভায় Matcher group() মেথড উদাহরণসহ ব্যাখ্যা

java.util.regex.Matcher ক্লাস বিভিন্ন ম্যাচ অপারেশন সম্পাদন করার একটি ইঞ্জিন প্রতিনিধিত্ব করে। এই ক্লাসের কোনো কনস্ট্রাক্টর নেই, আপনি java.util.regex.Pattern ক্লাসের matches() মেথড ব্যবহার করে এই ক্লাসের অবজেক্ট তৈরি/প্রाप्त করতে পারেন।

group() মেথড (Matcher ক্লাসের) শেষ ম্যাচের সময় মিলে যাওয়া ইনপুট সাবসিকোয়েন্স (subsequence) ফেরত দেয়।

উদাহরণ ১

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupExample {
    public static void main(String[] args) {
        String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> "
                   + "where <b>every</b> alternative <b>word</b> is <b>bold</b>. "
                   + "It <i>also</i> contains <i>italic</i> words</p>";
        
        // বোল্ড এবং ইটালিক ট্যাগের কন্টেন্ট মিলাতে রেগুলার এক্সপ্রেশন
        String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
        
        // Pattern অবজেক্ট তৈরি
        Pattern pattern = Pattern.compile(regex);
        
        // স্ট্রিং-এ কম্পাইল করা প্যাটার্ন মিলানো
        Matcher matcher = pattern.matcher(str);
        
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

আউটপুট

<b>is</b>
<b>example</b>
<b>script</b>
<b>every</b>
<b>word</b>
<b>bold</b>
<i>also</i>
<i>italic</i>

এই মেথডের আরেকটি ভেরিয়েন্ট একটি ইন্টিজার ভেরিয়েবল গ্রহণ করে যা গ্রুপকে প্রতিনিধিত্ব করে, যেখানে ক্যাপচার করা গ্রুপগুলো ১ থেকে শুরু করে বাম থেকে ডানে ইনডেক্স করা হয়।

উদাহরণ ২

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupTest {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between.";
        
        // Pattern অবজেক্ট তৈরি
        Pattern pattern = Pattern.compile(regex);
        
        // স্ট্রিং-এ কম্পাইল করা প্যাটার্ন মিলানো
        Matcher matcher = pattern.matcher(input);
        
        if(matcher.find()) {
            System.out.println("match: " + matcher.group(0));
            System.out.println("First group match: " + matcher.group(1));
            System.out.println("Second group match: " + matcher.group(2));
            System.out.println("Third group match: " + matcher.group(3));
        }
    }
}

আউটপুট

match: This is a sample Text, 1234, with numbers in between.
First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.
  1. জাভাতে Pattern pattern() মেথড - উদাহরণ সহ ব্যাখ্যা

  2. জাভাতে Pattern.matcher() মেথড - উদাহরণ সহ ব্যাখ্যা

  3. জাভাতে Matcher matches() মেথড - উদাহরণ সহ ব্যাখ্যা

  4. জাভাতে Matcher start() মেথড - উদাহরণ সহ ব্যাখ্যা