我想用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/