কম্পিউটার

জাভা রেগুলার এক্সপ্রেশন (RegEx) ব্যবহার করে কীভাবে সাদা স্থানগুলি সরানো যায়


রেগুলার এক্সপ্রেশন "\\s" একটি স্ট্রিং এর স্পেস এর সাথে মেলে। ReplaceAll() পদ্ধতি একটি স্ট্রিং গ্রহণ করে এবং একটি রেগুলার এক্সপ্রেশন প্রদত্ত স্ট্রিংয়ের সাথে মিলে যাওয়া অক্ষরগুলিকে প্রতিস্থাপন করে। একটি ইনপুট স্ট্রিং থেকে সমস্ত সাদা স্থান অপসারণ করতে, প্রতিস্থাপন করুন() উপরে উল্লিখিত রেগুলার এক্সপ্রেশন এবং ইনপুট হিসাবে একটি খালি স্ট্রিং বাইপাস করার পদ্ধতি।

উদাহরণ 1

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

উদাহরণ 2

একইভাবে, অ্যাপেন্ড রিপ্লেসমেন্ট() পদ্ধতিটি একটি স্ট্রিং বাফার এবং একটি প্রতিস্থাপন স্ট্রিং গ্রহণ করে এবং প্রদত্ত প্রতিস্থাপন স্ট্রিংয়ের সাথে মিলে যাওয়া অক্ষরগুলিকে যুক্ত করে এবং স্ট্রিং বাফারে যুক্ত করে৷

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);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      //Creating an empty string buffer
      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

উদাহরণ 3

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<str.length; i++) {
         result = result+str[i];
      }
      System.out.println("Result: "+result);
   }
}

আউটপুট

Result: Thisisasampletextwithspaces

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

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

  3. রেগুলার এক্সপ্রেশন \d জাভাতে গঠন করে

  4. জাভাতে রেগুলার এক্সপ্রেশন \S মেটাক্যারেক্টার