String.replaceAll() and \n line breaks

可紊 提交于 2019-12-20 06:47:48

问题


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


回答1:


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");



回答2:


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


来源:https://stackoverflow.com/questions/37328805/string-replaceall-and-n-line-breaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!