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

জাভা রেগুলার এক্সপ্রেশনে \s মেটাক্যারেক্টার ব্যাখ্যা

সাবএক্সপ্রেশন/মেটাক্যারেক্টার "\s" হোয়াইটস্পেস ইকুইভ্যালেন্ট ম্যাচ করে (স্পেস, ট্যাব, নিউলাইন, ক্যারেজ রিটার্ন, ফর্ম ফিড)।

উদাহরণ ১: হোয়াইটস্পেস গণনা

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\s";
        String input = "Hello how are you welcome to Tutorialspoint !";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        int count = 0;
        while (m.find()) {
            count++;
        }
        System.out.println("ম্যাচের সংখ্যা: " + count);
    }
}

আউটপুট

ম্যাচের সংখ্যা: 7

উদাহরণ ২: অতিরিক্ত স্পেস সরিয়ে এক স্পেস রাখা

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String args[]) {
        System.out.println("একটি স্ট্রিং দিন:");
        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("অনাবশ্য স্পেস সরানোর পর টেক্সট: \n" + result);
    }
}

আউটপুট

একটি স্ট্রিং দিন: hello this is a sample text with irregular spaces
অনাবশ্য স্পেস সরানোর পর টেক্সট: hello this is a sample text with irregular spaces

নোট: \\s+ এক বা অধিক liên tiếp হোয়াইটস্পেস ম্যাচ করে। replaceAll(" ") দিয়ে সব গুলোকে একক স্পেসে কনভার্ট করা হয়েছে।

  1. জাভা রেগুলার এক্সপ্রেশনে \w মেটাক্যারেক্টার ব্যাখ্যা

  2. জাভা রেগুলার এক্সপ্রেশনে \A মেটাক্যারেক্টার ব্যাখ্যা

  3. জাভা রেগুলার এক্সপ্রেশনে $ (ডলার) মেটাক্যারেক্টার ব্যাখ্যা

  4. জাভা রেগুলার এক্সপ্রেশনে ^ (ক্যারেরট) মেটাক্যারেক্টার ব্যাখ্যা