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();
}
The
replaceAll
method onString
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:Don't be confused by the name of the method - the difference between
replace
andreplaceAll
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: