Java Regex – Using String’s replaceAll method to replace newlines

Don’t use regex!. You only need a plain-text match to replace "\n".

Use replace() to replace a literal string with another:

string = string.replace("\n", " --linebreak-- ");

Note that replace() still replaces all occurrences, as does replaceAll() – the difference is that replaceAll() uses regex to search.

Leave a Comment