เมธอด replaceAll(String regex, String replacement) แทนที่ substring ที่ match regex ด้วย replacement string เพื่อลบคำเฉพาะ ให้ replace ด้วย empty string ""
ขั้นตอน
- อ่านเนื้อหาไฟล์ทั้งหมดเป็น String
- ใช้
replaceAll()แทนที่คำที่ต้องการลบด้วย"" - เขียนทับไฟล์เดิมด้วยผลลัพธ์
ตัวอย่างโค้ด
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class DeleteStringInFile {
public static String fileToString(String filePath) throws Exception {
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
sb.append(sc.nextLine());
}
return sb.toString();
}
public static void main(String[] args) throws FileNotFoundException {
String filePath = "D:\\sample.txt";
String content = fileToString(filePath);
System.out.println("Original: " + content);
// ลบคำ "Tutorialspoint" (word boundary \b ป้องกันลบบางส่วนของคำอื่น)
content = content.replaceAll("\\bTutorialspoint\\b", "");
// เขียนทับไฟล์
PrintWriter writer = new PrintWriter(new File(filePath));
writer.append(content);
writer.flush();
System.out.println("After delete: " + fileToString(filePath));
}
}
ผลลัพธ์
Original: Hello how are you welcome to Tutorialspoint
After delete: Hello how are you welcome to
Regex Pattern สำคัญ
| Pattern | ความหมาย | ตัวอย่าง match |
|---|---|---|
Tutorialspoint | ลบทุกที่เจอ (รวมในคำอื่น) | Tutorialspoint, MyTutorialspointX |
\\bTutorialspoint\\b | ลบเฉพาะคำเต็ม (word boundary) | Tutorialspoint ✓, MyTutorialspoint ✗ |
(?i)\\bTutorialspoint\\b | ไม่สนใจ case + word boundary | tutorialspoint, TUTORIALSPOINT |
\\s*Tutorialspoint\\s* | ลบคำพร้อม whitespace รอบๆ | " to Tutorialspoint " → " to " |