replace \n and \r\n with in java

It works for me. public class Program { public static void main(String[] args) { String str = “This is a string.\nThis is a long string.”; str = str.replaceAll(“(\r\n|\n)”, “<br />”); System.out.println(str); } } Result: This is a string.<br />This is a long string. Your problem is somewhere else.

String replace a Backslash

sSource = sSource.replace(“\\/”, “https://stackoverflow.com/”); String is immutable – each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable) replaceAll(..) uses regex. You don’t need that.

String.replaceAll single backslashes with double backslashes

The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex: string.replaceAll(“\\\\”, “\\\\\\\\”); But you don’t necessarily need regex for this, simply because you want an exact character-by-character replacement and you don’t need patterns here. So String#replace() should suffice: … Read more