replaceAll() মেথড একটি রেগুলার এক্সপ্রেশন এবং একটি স্ট্রিং প্যারামিটার হিসেবে গ্রহণ করে এবং বর্তমান স্ট্রিং-এর কন্টেন্ট দেওয়া রেগুলার এক্সপ্রেশনের সাথে ম্যাচ করে, ম্যাচ হলে ম্যাচ করা এলিমেন্টগুলো দেয়া স্ট্রিং দিয়ে রিপ্লেস করে।
replaceAll() মেথড ব্যবহার করে একটি ফাইল থেকে নির্দিষ্ট স্ট্রিং ডিলিট করতে:
- ফাইলের কন্টেন্ট স্ট্রিং হিসেবে রিট্রিভ করুন।
- প্রয়োজনীয় শব্দকে খালি স্ট্রিং দিয়ে replaceAll() মেথড ব্যবহার করে রিপ্লেস করুন।
- ফলাফল স্ট্রিংটি আবার ফাইলে রাইট করুন।
উদাহরণ
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StringExample {
public static String fileToString(String filePath) throws Exception {
String input = null;
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input);
}
return sb.toString();
}
public static void main(String args[]) throws FileNotFoundException {
String filePath = "D://sample.txt";
String result = fileToString(filePath);
System.out.println("Contents of the file: " + result);
result = result.replaceAll("\\bTutorialspoint\\b", "");
PrintWriter writer = new PrintWriter(new File(filePath));
writer.append(result);
writer.flush();
System.out.println("Contents of the file after replacing the desired word:");
System.out.println(fileToString(filePath));
}
}
আউটপুট
Contents of the file: Hello how are you welcome to Tutorialspoint
Contents of the file after replacing the desired word: Hello how are you welcome to
ব্যাখ্যা: \\bTutorialspoint\\b রেগেক্স "Tutorialspoint" শব্দটি শব্দের সীমানায় (word boundary) ম্যাচ করে। এটি "TutorialspointXYZ"-কে ম্যাচ করবে না। PrintWriter ব্যবহার করে ফাইল ওভাররাইট করা হয়েছে।