মেটা ক্যারেক্টার \s স্পেস ম্যাচ করে এবং + ইন্ডিকেট করে স্পেসের ঘটনা এক বা একাধিক বার। তাই রেগুলার এক্সপ্রেশন \\s+ সকল স্পেস ক্যারেক্টার (সিঙ্গল বা মাল্টিপল) ম্যাচ করে। একাধিক স্পেসকে একক স্পেসে রিপ্লেস করতে:
ইনপুট স্ট্রিংকে উপরের রেগুলার এক্সপ্রেশনসহ ম্যাচ করিয়ে ফলাফলগুলোকে একক স্পেস " " দিয়ে রিপ্লেস করুন।
উদাহরণ ১: 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[]) {
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 = 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
উদাহরণ ২: String.replaceAll() ব্যবহার করে
import java.util.Scanner;
public class Test {
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+";
// প্যাটার্নকে একক স্পেসে রিপ্লেস
String result = input.replaceAll(regex, " ");
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