Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace "\n" but not ">\n" in a string

Tags:

java

html

regex

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.

like image 938
Marco C Avatar asked Nov 19 '25 13:11

Marco C


1 Answers

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 >.

like image 122
alex Avatar answered Nov 21 '25 02:11

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!