কম্পিউটার

জাভাতে Matcher ReplaceAll() পদ্ধতি উদাহরণ সহ


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

এই (Matcher) ক্লাসের replaceAll() পদ্ধতিটি একটি স্ট্রিং মান গ্রহণ করে, প্রদত্ত স্ট্রিং মান দিয়ে ইনপুটে সমস্ত মিলে যাওয়া অনুগামীগুলিকে প্রতিস্থাপন করে এবং ফলাফল প্রদান করে৷

উদাহরণ 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Retrieving Pattern used
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      //Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
      System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
   }
}

আউটপুট

Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !:
Hello! How ! are! you !! welcome to T!utorials!point
-এ স্বাগতম

উদাহরণ 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match spaces (one or more)
      String regex = "\\s+";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //Replacing all space characters with single space
      String result = matcher.replaceAll(" ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}

আউটপুট

Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces

  1. উদাহরণ সহ জাভাতে প্যাটার্ন প্যাটার্ন() পদ্ধতি

  2. উদাহরণ সহ জাভাতে প্যাটার্ন ম্যাচার() পদ্ধতি

  3. উদাহরণ সহ জাভাতে ম্যাচার ম্যাচ() পদ্ধতি

  4. উদাহরণ সহ জাভাতে ম্যাচার স্টার্ট() পদ্ধতি