Printing a replaced line in a new text file

前端 未结 1 1787
后悔当初
后悔当初 2021-01-27 22:42

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 co

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 23:15

    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.

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

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

    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) {
    

    0 讨论(0)
提交回复
热议问题