2014-06-19 39 views
0

我想编辑一个matlab文件并在某些特定行中替换某些编码部分的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(); 
} 

回答

5

replaceAll方法上String将正则表达式作为参数,并在正则表达式的一些字符有特殊的含义,比如在你的表达括号。

只需使用replace方法来代替,这需要文字字符串:

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

不要通过该方法的名字迷惑 - replacereplaceAll之间的差别并不在他们更换了多少次,但区别在于第一个采用文字字符串,第二个采用正则表达式。这是在Javadoc:

替换这个字符串字面匹配目标与 指定面值替换序列序列的每个子

public String replace(CharSequence target, CharSequence replacement) { 
+0

噢谢谢。我不知道replace和replaceAll之间的区别。 – user3211165