user1220699
user1220699

Reputation: 1

Java String Replacement

I have a string like this in a file

<script>
Evening</script>

I have written a code to replace this string but it's not identifying the newline character i,e. I want to replace above string with:

<h1>Done</h1>

code goes like this:

package stringreplace;
import java.io.*;

import org.omg.CORBA.Request;

public class stringreplace {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FileReader fr = null;
        BufferedReader br = null;

        try
        {
             fr = new FileReader("G://abc.html");
             br = new BufferedReader(fr);

             String newtext="";
             String line="";

             String matchExist1 = "<script>\r\nEvening</script>";
             String newpattern = "<h1>Done</h1>";

             String matchExist2 = "</body>";
             String newpattern2 = "<script>alpha</script></body>";

             StringBuffer sb = new StringBuffer();

             while((line=br.readLine())!=null)
             {
                int ind2 = line.indexOf(matchExist1);
                System.out.println(ind2);
                int ind3 = line.indexOf(matchExist2);
                if((ind2==-1) || (ind3==-1))
                 {
                    line = line.replaceFirst(matchExist1,newpattern);
                    line = line.replaceFirst(matchExist2,newpattern2);
                    sb.append(line+"\n");   
                 }
                //sb.append(line+"\n");
                else if((ind2!=-1) || (ind3!=-1))
                 {
                    String tag = "</body>";
                    line = line.replaceFirst("</body>",tag);
                    sb.append(line+"\n");
                 }
            }
             br.close();

             FileWriter fw = new FileWriter("G://abc.html");
             fw.write(sb.toString());
             fw.close();

             System.out.println("done");
             System.out.println(sb);

        }
    catch (Exception e)
        {
         System.out.println(e);
        }

    }

}

But it is not identifying newline character.

Upvotes: 0

Views: 300

Answers (2)

mac
mac

Reputation: 5647

Since you are reading only one input line at a time you can hardly expect to match a pattern that spans two lines.You must first fix your read to have a least two lines in it. Once you've done that, @sterna's answer will do the trick

Upvotes: 3

stema
stema

Reputation: 92976

I think you can't be sure about how your newline looks like. So I would not match for a specific sequence instead use \s+ this is at least one whitespace character and all newline characters are included.

String matchExist1 = "<script>\\s+Evening</script>";

Edit:
Of course, you have to fix at first the problem mgc described (+1). And then you can make use of my answer!

Upvotes: 1

Related Questions