I’m writing code that’s supposed to remove actual line breaks from a block of text and replace them with the String “\n”. Then, when the String is read at another time, it should replace the line breaks (in other words, search for all “\n” and insert \n. However, while the first conversion works fine, it’s not doing the latter. It seems as though the second replace is doing nothing. Why?
The replace:
theString.replaceAll(Constants.LINE_BREAK, Constants.LINE_BREAK_DB_REPLACEMENT);
The re-replace:
theString.replaceAll(Constants.LINE_BREAK_DB_REPLACEMENT, Constants.LINE_BREAK);
The constants:
public static final String LINE_BREAK = "\n";
public static final String LINE_BREAK_DB_REPLACEMENT = "\\\\n";
In
String.replaceAll(regex, replacement), both the regex string and replacement string treat backslash as an escape character:regexrepresents a regular expression, which escapes a backslash as\\replacementis a replacement string, which also escapes backslashes:This means backslashes must be escaped in both parameters. Further, string constants also use backslash as an escape character, so backslashes in string constants passed to the method must be double-escaped (see also this question).
This works fine for me:
You can also use the
Matcher.quoteReplacement()method to treat the replacement string as a literal: