java.util.regex.Matcher ক্লাস বিভিন্ন ম্যাচ অপারেশন সম্পাদন করার একটি ইঞ্জিন প্রতিনিধিত্ব করে। এই ক্লাসের কোনো কনস্ট্রাক্টর নেই, আপনি java.util.regex.Pattern ক্লাসের matches() মেথড ব্যবহার করে এই ক্লাসের অবজেক্ট তৈরি/প্রাপ্ত করতে পারেন।
এই (Matcher) ক্লাসের replaceAll() মেথড একটি স্ট্রিং মান গ্রহণ করে, ইনপুট-এ সমস্ত মিলে যাওয়া সাবসিকোয়েন্সগুলোকে দেওয়া স্ট্রিং মান দিয়ে প্রতিস্থাপন করে এবং ফলাফল ফেরত দেয়।
উদাহরণ ১
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 = "[#%&*]";
// 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 " + count + " special characters [# % & *] in the given text");
// সব বিশেষ ক্যারেক্টার [# % & *] কে ! দিয়ে প্রতিস্থাপন
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
উদাহরণ ২
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
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.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