在新文本文件中打印替换行 [英] Printing a replaced line in a new text file

查看:99
本文介绍了在新文本文件中打印替换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编辑matlab文件并在某些特定行中替换某些编码部分init。但是,使用下面的格式进行更改它根本不会更改行上下文。 (它将打印相同的旧行)。知道我做错了什么吗? 'replaceAll'不适合用行中的其他单词替换某些单词吗?

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?

提前致谢。

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 方法将正则表达式作为参数,在正则表达式中,某些字符具有特殊含义,例如表达式中的括号。

The replaceAll method on String takes a regular expression as an argument, and in regular expressions some characters have special meanings, such as the parentheses in your expression.

只需使用替换方法,取而代之的是lite ral strings:

Simply use the replace method instead, which takes literal strings:

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

不要混淆方法的名称 - 之间的区别替换 replaceAll 不是他们替换了多少次,但不同之处在于第一个采用文字字符串而第二个采用文字字符串正则表达式。它位于Javadoc中:

Don't be confused by the name of the method - the difference between replace and replaceAll 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:


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

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.



public String replace(CharSequence target, CharSequence replacement) {

这篇关于在新文本文件中打印替换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆