রেগুলার এক্সপ্রেশন "\\s" একটি স্ট্রিং-এ সাদা স্থান (spaces) মিলাতে ব্যবহৃত হয়। replaceAll() মেথড একটি স্ট্রিং এবং একটি রেগুলার এক্সপ্রেশন গ্রহণ করে, মিলে যাওয়া ক্যারেক্টারগুলোকে দেওয়া স্ট্রিং-এ প্রতিস্থাপন করে। ইনপুট স্ট্রিং-এ থেকে সমস্ত সাদা স্থান সরাতে, উপরে উল্লিখিত রেগুলার এক্সপ্রেশন এবং একটি খালি স্ট্রিং পাস করে replaceAll() মেথডটি কল করতে হয়।
উদাহরণ ১
public class RemovingWhiteSpaces {
public static void main(String args[]) {
String input = "Hi welcome to tutorialspoint";
String regex = "\\s";
String result = input.replaceAll(regex, "");
System.out.println("Result: " + result);
}
}
আউটপুট
Result: Hiwelcometotutorialspoint
উদাহরণ ২
বিভিন্নভাবে, appendReplacement() মেথড একটি স্ট্রিং বাফার এবং একটি প্রতিস্থাপন স্ট্রিং গ্রহণ করে, মিলে যাওয়া ক্যারেক্টারগুলোকে দেওয়া প্রতিস্থাপন স্ট্রিং-এ প্রতিস্থাপন করে এবং স্ট্রিং বাফারে যুক্ত করে।
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "\\s";
String constants = "";
System.out.println("Input string: \n" + input);
// Pattern অবজেক্ট তৈরি
Pattern pattern = Pattern.compile(regex);
// স্ট্রিং-এ কম্পাইল করা প্যাটার্ন মিলানো
Matcher matcher = pattern.matcher(input);
// খালি একটি স্ট্রিং বাফার তৈরি
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants + matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n" + sb.toString() + constants);
}
}
আউটপুট
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
উদাহরণ ৩
public class Just {
public static void main(String args[]) {
String input = "This is a sample text with spaces";
String str[] = input.split(" ");
String result = "";
for(int i=0; i
আউটপুট
Result: Thisisasampletextwithspaces