简体   繁体   中英

How to replace “\n” but not “>\n” in a string

Using Java how is it possible replace all "\\n" but not ">\\n" with "<br/>" ?

I need it because I want add a "<br/>" if I have a new line on plain text, but not if I have HTML.

Use a negative lookbehind .

String str = "\n>\n\n";

str = str.replaceAll("(?<!>)\n", "<br />");

This will match the \\n , and then backtrack a character to ensure the preceding character wasn't a > .

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