繁体   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