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
From the javadoc of
String#replaceAll(String, String)
:You still need 2 backslashes, as
\
is a metachar for string literals.You can also use 4 backslashes without
Matcher.quoteReplacement
:\
in the output\
, as\
is a metachar for replacement strings:\\
\
, as\
is a metachar for string literals:\\\\
Don't use
replaceAll()
!replaceAll()
does a regex search and replace, but your task doesn't need regex - just use the plain text versionreplace()
, also replaces all occurrences.You need a literal backslash, which is coded as two backslashes in a Java String literal:
Output: