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

জাভা রেগেক্সে matches() এবং find() মেথডের পার্থক্য

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

Matcher ক্লাসের matches() এবং find() উভয় মেথডই রেগুলার এক্সপ্রেশন অনুযায়ী ইনপুট স্ট্রিং-এ ম্যাচ খুঁজে বের করতে চেষ্টা করে। ম্যাচ পেলে উভয়ই true ফেরত দেয় এবং ম্যাচ না পেলে উভয়ই false ফেরত দেয়।

মূল পার্থক্য হচ্ছে matches() মেথড দেওয়া ইনপুট-এর পুরো অঞ্চল মিলাতে চেষ্টা করে অর্থাৎ আপনি যদি একটি লাইনে অঙ্ক খুঁজতে চান তবে এই মেথড true ফেরত দেবে কেবল তখনই যখন ইনপুট-এর অঞ্চলের সব লাইনে অঙ্ক থাকে।

উদাহরণ ১

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

public class Test {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between. "
                     + "\n This is the second line in the text "
                     + "\n This is third line in the text";
        
        // Pattern অবজেক্ট তৈরি
        Pattern pattern = Pattern.compile(regex);
        
        // Matcher অবজেক্ট তৈরি
        Matcher matcher = pattern.matcher(input);
        
        if(matcher.matches()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

আউটপুট

Match not found

অন্যদিকে, find() মেথড প্যাটার্নের সাথে মিলে যাওয়া পরবর্তী সাবস্ট্রিং খুঁজে বের করতে চেষ্টা করে অর্থাৎ অঞ্চলে কমপক্ষে একটি মিল পেলে এই মেথড true ফেরত দেয়।

নিচের উদাহরণটি বিবেচনা করলে, আমরা মাঝপথে অঙ্ক থাকা একটি নির্দিষ্ট লাইন মিলাতে চাচ্ছি।

উদাহরণ ২

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

public class Test {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between. "
                     + "\n This is the second line in the text "
                     + "\n This is third line in the text";
        
        // Pattern অবজেক্ট তৈরি
        Pattern pattern = Pattern.compile(regex);
        
        // Matcher অবজেক্ট তৈরি
        Matcher matcher = pattern.matcher(input);
        
        // System.out.println("Current range: " + input.substring(regStart, regEnd));
        if(matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

আউটপুট

Match found
  1. জাভাতে Iterator এবং Enumeration-এর পার্থক্য

  2. জাভাতে ArrayList এবং HashSet-এর পার্থক্য

  3. JRE এবং JDK-এর পার্থক্য

  4. জাভা এবং জাভাস্ক্রিপ্টের মধ্যে পার্থক্য কী?