মেটা অক্ষর “\\s” স্পেস মেলে এবং + এক বা একাধিকবার স্পেসগুলির উপস্থিতি নির্দেশ করে, তাই, রেগুলার এক্সপ্রেশন \\S+ সমস্ত স্পেস অক্ষরের (একক বা একাধিক) সাথে মেলে। অতএব, একটি একক স্পেস দিয়ে একাধিক স্পেস প্রতিস্থাপন করুন।
উপরের রেগুলার এক্সপ্রেশনের সাথে ইনপুট স্ট্রিং মিলান এবং ফলাফলগুলিকে একক স্থান “” দিয়ে প্রতিস্থাপন করুন।
উদাহরণ 1
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();
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
উদাহরণ 2
import java.util.Scanner;
public class Test {
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 space(s)
String regex = "\\s+";
//Replacing the pattern with single space
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