我有一个字符串如下:
\ r \ n \ r \ n一些文字blahblah \ r \ n \ r \ n \ r \ n \ r \ n其他一些文字\ r \ n \ r \ n \ r \ n \ r \ n blah blah blah \ r \ n
我想用一个<br>
标记替换多个换行符的任何实例,并且还要替换<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>")
答案 0 :(得分:0)
也许尝试这个(不是正则表达式,但有效:)),这将支持\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>"
答案 1 :(得分:0)
这是怎么回事:
Regex.Replace(text, @"([\r\n]\s*)+", "<br>")
或者如果您不希望它在换行符之后占用空间:
Regex.Replace(text, @"[\r\n](\s*[\r\n])+", "<br>")
答案 2 :(得分:-2)
这应该做的工作
string myString = "\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";
myString = Regex.Replace(myString, @"(?:\r\n *){1,2} *", "<br>");
将产生
<br>Some text blahblah <br><br>Some other text <br><br>blah blah blah <br>