用一个单位替换所有连续的“\ r \ n或\ n”

时间:2012-10-05 17:00:42

标签: java html regex string

目前,我正在使用这两个替代品显示我从DB获得的消息:

text = text.replace("\r\n", "<br />");
text = text.replace("\n", "<br />");

但问题是,如果有很多连续的“\ n”,我会有很多白色或空格,我只想把它们全部放在一起。那你的建议是什么?是否有快速替换方法使所有连续的\ n \ n \ n \ n \ n \ n \ n只有一个br?

3 个答案:

答案 0 :(得分:6)

您可以使用量词+来表示1个或更多.. 此外,*表示0或更多..

text = text.replaceAll("\n+", "<br />");

text = text.replaceAll("[\n\r]+", "<br />");

答案 1 :(得分:2)

如果您有多个\r\n\n,其中包含其他内容,您也可以使用

text.replaceAll("(\r\n)+", "<br />")
    .replaceAll("\n+", "<br />");

答案 2 :(得分:1)

你试过这个:

text = text.replace("(\r\n)+", "<br />");
text = text.replace("\n+", "<br />");

+表示前一场比赛的“一个或多个”。

相关问题