String.replaceAll() and \n line breaks

2020-05-02 04:07发布

I try to explain my problem with a little example. I implemented version 1 and version 2, but I didn't get the desired result. Which replacement-parameter do I have to use to get the desired result with the replaceAll method ?

Version 1:

String s = "TEST";
s = s.replaceAll("TEST", "TEST\nTEST");
System.out.println(s);

Output:

TEST

TEST



Version 2:

String s = "TEST";
s = s.replaceAll("TEST", "TEST\\nTEST");
System.out.println(s);

Output:

TESTnTEST



Desired Output:

TEST\nTEST

2条回答
贼婆χ
2楼-- · 2020-05-02 04:25

From the javadoc of String#replaceAll(String, String):

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

s = s.replaceAll("TEST", Matcher.quoteReplacement("TEST\\nTEST"));

You still need 2 backslashes, as \ is a metachar for string literals.


You can also use 4 backslashes without Matcher.quoteReplacement:

  • you want one \ in the output
  • you need to escape it with \, as \ is a metachar for replacement strings: \\
  • you need to escape both with \, as \ is a metachar for string literals: \\\\
s = s.replaceAll("TEST", "TEST\\\\nTEST");
查看更多
老娘就宠你
3楼-- · 2020-05-02 04:49

Don't use replaceAll()!

replaceAll() does a regex search and replace, but your task doesn't need regex - just use the plain text version replace(), also replaces all occurrences.

You need a literal backslash, which is coded as two backslashes in a Java String literal:

String s = "TEST";
s = s.replace("TEST", "TEST\\nTEST");
System.out.println(s);

Output:

TEST\nTEST
查看更多
登录 后发表回答