简体   繁体   中英

I am trying to replace the occurrences of \r to \r\n. It is also replacing the character before and after \r. What am I doing wrong here?

String abc = "ABC\n\rDEF\rGHI\nJKL\n\rMNO\r\tPQR\t";
String cde = abc.replaceAll("[^\n]\r[^\t]", "\n\r");
System.out.println(cde);

The \r should be not be surrounded by \n or \t. For instance, I do not want to replace \n\r to \n\n\r.

Expected: "ABC\n\rDEF\n\rGHI\nJKL\n\rMNO\r\tPQR\t"
Actual: "ABC\n\rDE\n\rHI\nJKL\n\rMNO\r\tPQR\t"

There is the Linux line ending \n and the Windows line ending \r\n .

s = s.replaceAll("\\R", "\r\n");

Uses the regex pattern for any line ending \R to replace it.

Re the comment left above (Sorry for the slow response)

Here is a regex101 sample of the groupings.

Note the need to use the escape character '\' which may be required depending on your language. I used the expression

([^\\n])\\r([^\\t])

and the substitution string

$1\\n\\r$2

The result as shown is

ABC\n\rDEF\n\rGHI\nJKL\n\rMNO\r\tPQR\t

regex101 例子

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM