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

জাভায় রেগুলার এক্সপ্রেশন ব্যবহার করে স্ট্রিং থেকে স্বরবর্ণ (Vowels) সরানো

সহজ ক্যারেক্টার ক্লাস "[ ]" তার মধ্যে নির্দিষ্ট সমস্ত ক্যারেক্টার মিলাতে ব্যবহৃত হয়। নিচের এক্সপ্রেশন xyz ব্যতীত সমস্ত ক্যারেক্টার মিলায়:

"[xyz]"

একইভাবে, নিচের এক্সপ্রেশন দেওয়া ইনপুট স্ট্রিং-এ থাকা সব স্বরবর্ণ মিলায়:

"([^aeiouAEIOU0-9\\W]+)";

তারপর replaceAll() মেথড ব্যবহার করে মিলে যাওয়া ক্যারেক্টারগুলোকে খালি স্ট্রিং "" দিয়ে প্রতিস্থাপন করে সরানো যায়।

উদাহরণ ১

public class RemovingVowels {
    public static void main(String args[]) {
        String input = "Hi welcome to tutorialspoint";
        String regex = "[aeiouAEIOU]";
        String result = input.replaceAll(regex, "");
        System.out.println("Result: " + result);
    }
}

আউটপুট

Result: H wlcm t ttrlspnt

উদাহরণ ২

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

public class Test {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string: ");
        String input = sc.nextLine();
        String regex = "[aeiouAEIOU]";
        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
Input string: this is a sample text
Result: ths s smpl txtiiaaee
  1. জাভাস্ক্রিপ্টে স্ট্রিং থেকে কমা (,) বা যেকোনো সাবস্ট্রিং সরানো

  2. অ্যান্ড্রয়েড TextView স্ট্রিং-এ স্বরবর্ণ মুছে ফেলার পদ্ধতি

  3. জাভাতে দেওয়া স্ট্রিং থেকে HTML ট্যাগ সরানো

  4. জাভাতে রেগুলার এক্সপ্রেশন ব্যবহার করে স্ট্রিং থেকে নম্বর বের করা