2

I want to replace a word from a txt file in java. I already have my regular expression and the method for reading the txt file from java. But i have no idea how to replace a word from it using mu regualar expression.

Any suggestion or example?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Calosch
  • 29
  • 1
  • 2
  • Maybe this thread http://stackoverflow.com/questions/632204/java-string-replace-using-regular-expressions will help you? – Reuel Ribeiro Mar 27 '17 at 14:22
  • You can use regex to modify strings, not files. You need other tools to read text from file and convert it to string, then apply regex, then store string into file. So you need proper Readers to read text from file and Writers to write text to file. – Pshemo Mar 27 '17 at 14:22
  • Possible duplicate of [Find and replace words in a text file using java](http://stackoverflow.com/questions/29056132/find-and-replace-words-in-a-text-file-using-java) – Seymore Mar 27 '17 at 14:23

2 Answers2

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

}

Anurag Dadheech
  • 629
  • 1
  • 5
  • 14
0

Parse the file into one string.Then replace all instances of word with new word.

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

Then write the new text to a file

 FileWriter writer = new FileWriter("out.txt");
 writer.write(response);
Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106