简体   繁体   English

如何在字符串中替换“\\ n”而不是“> \\ n”

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

Using Java how is it possible replace all "\\n" but not ">\\n" with "<br/>" ? 使用Java如何用"<br/>"替换所有"\\n"而不是">\\n" "<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. 我需要它,因为如果我在纯文本上有一个新行,我想添加一个"<br/>" ,但如果我有HTML,则不需要。

Use a negative lookbehind . 使用负面的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 > . 这将匹配\\n ,然后回溯一个字符以确保前面的字符不是>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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