gpt4 book ai didi

c# - 正则表达式用
标签替换多个换行符

转载 作者:行者123 更新时间:2023-11-30 18:47:39 25 4
gpt4 key购买 nike

我有一个字符串如下:

\r\n \r\n Some text blahblah \r\n \r\n \r\n \r\n Some other text \r\n \r\n \r\n \r\n blah blah blah \r\n

我想用一个 <br> 替换多个换行符的任何实例标记以及任何单个\r\n 到 <br>

所以上面的文字应该是这样的:

<br>  Some text blahblah <br><br> Some other text <br><br> blah blah blah <br>

我已经试过了,但它没有考虑到之间的空格:\r\n\r\n

Regex.Replace(text, @"[\r\n]+", "<br>")

最佳答案

也许试试这个(不是正则表达式,但有效:)),这将支持 \r\n 的奇数/偶数,并且如果 \r 则将标签添加到开始和结束\n 丢失。

 var result = string.Concat(text.Split(new char[] { '\r', '\n' })
.Where(l => !string.IsNullOrWhiteSpace(l))
.Select(s => string.Format("<br> {0} <br>",s)));

结果:

\r\n \r\n Some text blahblah \r\n \r\n \r\n \r\n Some other text \r\n \r\n \r\n \r\n blah blah blah \r\n
"<br> Some text blahblah <br><br> Some other text <br><br> blah blah blah <br>"

\r\n \r\n Some text \r\n Some other \r\n \r\n \r\n blah blah blah
"<br> Some text <br><br> Some other <br><br> blah blah blah <br>"

关于c# - 正则表达式用 <br> 标签替换多个换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15291402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com