java - 如何用java中的正则表达式替换txt文件中的单词

标签 java regex

我想用java替换txt文件中的单词。我已经有了我的正则表达式和从java读取txt文件的方法。但我不知道如何使用 mu 正则表达式替换其中的单词。

有什么建议或例子吗?

最佳答案

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();
     }
 }

}

关于java - 如何用java中的正则表达式替换txt文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048988/

相关文章:

java - 两个单独的 getTime() 调用在不同时间返回相同的值

java - 为什么这个函数的输出是1?

ios - 通过正则表达式的表情符号数字

php - 获取 Twig 模板文件中使用的所有变量

regex - 为什么顺序在 sed 中的这个转义字符类中很重要?

java - 用于不同类型输入的不同 Java 扫描器

java - 如何在 Cassandra 中使用 Spark 获取行范围

java - 阅读 Nashorn JO4 和 NativeArray

mysql - 使用正则表达式仅获取数字

javascript - 如何删除双括号中的字符串?