我正在尝试编辑 matlabfile 并替换某些特定行中的一些编码部分 init 。但是,使用下面的格式进行更改根本不会更改行上下文。 (它将打印相同的旧行)。知道我做错了什么吗? 'replaceAll' 不适合将行中的某些单词替换为其他单词?
提前致谢。
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
方法上String
采用正则表达式作为参数,并且在正则表达式中某些字符具有特殊含义,例如表达式中的括号。
只需使用replace
方法,它接受文字字符串:
String newline = line.replace("stream.Values(strmatch('Test',stream.Components,'exact'))", "New Data");
不要被方法的名称混淆 - 之间的区别replace
and replaceAll
不在于它们替换了多少次,而区别在于第一个采用文字字符串,第二个采用正则表达式。它在 Javadoc 中:
取代每个子串与文字目标匹配的字符串的
具有指定文字替换序列的序列。
public String replace(CharSequence target, CharSequence replacement) {
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)