Java 在新文本文件中打印替换的行
我试图编辑一个MATLAB文件,并在某些特定行中替换一些编码部分init。但是,使用下面的格式进行更改时,它根本不会更改行上下文。(它将打印相同的旧行)。你知道我做错了什么吗?”“replaceAll”不适合将行中的某些单词替换为其他单词 提前谢谢Java 在新文本文件中打印替换的行,java,java.util.scanner,printwriter,replaceall,Java,Java.util.scanner,Printwriter,Replaceall,我试图编辑一个MATLAB文件,并在某些特定行中替换一些编码部分init。但是,使用下面的格式进行更改时,它根本不会更改行上下文。(它将打印相同的旧行)。你知道我做错了什么吗?”“replaceAll”不适合将行中的某些单词替换为其他单词 提前谢谢 try { PrintWriter out = new PrintWriter(new FileWriter(filenew, true)); Scanner scanner = new Scanner(file); whi
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();
}
String
上的replaceAll
方法将正则表达式作为参数,在正则表达式中,某些字符具有特殊含义,例如表达式中的括号
只需使用replace
方法即可,该方法采用文本字符串:
String newline = line.replace("stream.Values(strmatch('Test',stream.Components,'exact'))", "New Data");
不要被方法的名称所迷惑,replace
和replaceAll
之间的区别不在于它们替换了多少次,而在于第一个方法采用文本字符串,第二个方法采用正则表达式。它在Javadoc中:
替换此字符串中与文字目标匹配的每个子字符串
具有指定的文字替换序列的序列
String
上的replaceAll
方法将正则表达式作为参数,在正则表达式中,某些字符具有特殊含义,例如表达式中的括号
只需使用replace
方法即可,该方法采用文本字符串:
String newline = line.replace("stream.Values(strmatch('Test',stream.Components,'exact'))", "New Data");
不要被方法的名称所迷惑,replace
和replaceAll
之间的区别不在于它们替换了多少次,而在于第一个方法采用文本字符串,第二个方法采用正则表达式。它在Javadoc中:
替换此字符串中与文字目标匹配的每个子字符串
具有指定的文字替换序列的序列
哦,谢谢你。我不知道replace和replaceAll之间的区别。哦,谢谢。我不知道replace和replaceAll之间的区别。