Printing a replaced line in a new text file

2020-05-06 10:35发布

问题:

I am trying to edit a matlabfile and replace some of the coding parts init in some specific lines. However, using the format below to make the changes it wont change the line context at all. (it will print the same old line). Any idea what am I doing wrong? 'replaceAll' is not suitable to replace some words with some others in the lines?

Thanks in advance.

try {
    PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        if (line.contains("stream.Values(strmatch('Test',stream.Components,'exact'))") {  
            String newline = line.replaceAll("stream.Values(strmatch('Test',stream.Components,'exact'))", "New Data");

            out.println(newline);
            System.out.println(newline);
        } else {
            out.write(line);
            out.write("\n");
        }
    }     // while loop

    out.flush();
    out.close();
    scanner.close();



} catch (IOException e)  {
    e.printStackTrace();
}

回答1:

The replaceAll method on String takes a regular expression as an argument, and in regular expressions some characters have special meanings, such as the parentheses in your expression.

Simply use the replace method instead, which takes literal strings:

String newline = line.replace("stream.Values(strmatch('Test',stream.Components,'exact'))", "New Data");

Don't be confused by the name of the method - the difference between replace and replaceAll is not in how many times they replace, but the difference is in that the first one takes literal strings and the second one takes a regular expression. It's in the Javadoc:

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

public String replace(CharSequence target, CharSequence replacement) {