কম্পিউটার টিউটোরিয়াল

জাভা রেজেক্স ব্যবহার করে স্ট্রিং-এ একাধিক স্পেসকে একক স্পেসে রিপ্লেস করা

মেটা ক্যারেক্টার \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
  1. জাভা রেগেক্স দিয়ে যেকোনো ক্যারেক্টার ম্যাচ করা (.)

  2. জাভাতে flexjson ব্যবহার করে JSON র‍্যাপ (Wrap) কীভাবে করবেন?

  3. জাভাতে রেগেক্স ব্যবহার করে স্ট্রিং থেকে HTML ট্যাগ এক্সট্র্যাক্ট করা

  4. পাইথনে স্ট্রিংয়ের ট্যাবকে স্পেসে কনভার্ট করা (Expand Tabs)