簡體   English   中英

如何用Java中的正則表達式替換txt文件中的單詞

[英]How to replace a word from txt file with regular expression in java

我想替換Java中txt文件中的單詞。 我已經有了我的正則表達式和從Java讀取txt文件的方法。 但我不知道如何使用mu regualar表達式替換單詞。

有什么建議或例子嗎?

public class BTest
{
 public static void main(String args[])
     {
     try
         {
         File file = new File("file.txt");
         BufferedReader reader = new BufferedReader(new FileReader(file));
         String line = "", oldtext = "";
         while((line = reader.readLine()) != null)
             {
             oldtext += line + "\r\n";
         }
         reader.close();
         // replace a word in a file
         String newtext = oldtext.replaceAll("drink", "Love");

         //To replace a line in a file
         //String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");

         FileWriter writer = new FileWriter("file.txt");
         writer.write(newtext);writer.close();
     }
     catch (IOException ioe)
         {
         ioe.printStackTrace();
     }
 }

}

將文件解析為一個字符串,然后用新單詞替換單詞的所有實例。

 String response = "test string".replaceAll("regex here", "new text");

然后將新文本寫入文件

 FileWriter writer = new FileWriter("out.txt");
 writer.write(response);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM