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

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

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

এই (Matcher) ক্লাসের replaceFirst() মেথড একটি স্ট্রিং মান গ্রহণ করে এবং, ইনপুট টেক্সট-এ প্রথম মিলে যাওয়া সাবসিকোয়েন্সকে দেওয়া স্ট্রিং মান দিয়ে প্রতিস্থাপন করে এবং ফলাফল ফেরত দেয়।

উদাহরণ ১

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

public class ReplaceFirstExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        String regex = "[#]";
        
        // Pattern অবজেক্ট তৈরি
        Pattern pattern = Pattern.compile(regex);
        
        // Matcher অবজেক্ট তৈরি
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        
        while(matcher.find()) {
            count++;
        }
        
        // ব্যবহৃত Pattern পুনরুদ্ধার
        System.out.println("The are character # occurred " + count + " times in the given text");
        
        // প্রথম অনভূমিকে @ দিয়ে প্রতিস্থাপন
        String result = matcher.replaceFirst("@");
        System.out.println("Text after replacing the first occurrence of # with @ \n" + result);
    }
}

আউটপুট

Enter input text: Enter input text: Hello# How # are# you #welcome to Tutorials#point
The are character # occurred 5 times in the given text
Text after replacing the first occurrence of # with @
Hello@ How # are# you #welcome to Tutorials#point

উদাহরণ ২

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

public class ReplaceFirstExample {
    public static void main(String args[]) {
        // ব্যবহারকারীর কাছ থেকে স্ট্রিং পড়া
        System.out.println("Enter a String");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String regex = "\\s+";
        
        // রেগুলার এক্সপ্রেশন কম্পাইল
        Pattern pattern = Pattern.compile(regex);
        
        // Matcher অবজেক্ট পাওয়া
        Matcher matcher = pattern.matcher(input);
        
        // সব স্পেস ক্যারেক্টারকে একক স্পেস দিয়ে প্রতিস্থাপন
        String result = matcher.replaceFirst("_");
        System.out.print("Text after replacing the first space with '_': \n" + result);
    }
}

আউটপুট

Enter a String hello this is a sample text with irregular spaces
Text after replacing the first space with '_':
hello_this is a sample text with irregular spaces
  1. জাভাতে Pattern pattern() মেথড - উদাহরণ সহ ব্যাখ্যা

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

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

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