【问题标题】:Printing a replaced line in a new text file在新文本文件中打印替换行
【发布时间】:2014-06-19 09:42:55
【问题描述】:

我正在尝试编辑 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();
}

【问题讨论】:

    标签: java java.util.scanner printwriter replaceall


    【解决方案1】:

    String 上的 replaceAll 方法将正则表达式作为参数,而在正则表达式中,某些字符具有特殊含义,例如表达式中的括号。

    只需使用 replace 方法代替,它接受文字字符串:

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

    不要被方法名弄糊涂了——replacereplaceAll 的区别不在于它们替换了多少次,而区别在于第一个采用文字字符串,而第二个采用文字字符串接受一个正则表达式。它在 Javadoc 中:

    替换此字符串中与文字目标匹配的每个子字符串 具有指定文字替换序列的序列。

    public String replace(CharSequence target, CharSequence replacement) {
    

    【讨论】:

    • 哦,谢谢。我不知道 replace 和 replaceAll 之间的区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多