gpt4 book ai didi

c# - 替换
 标签之间的换行符

转载 作者:太空狗 更新时间:2023-10-30 01:19:56 25 4
gpt4 key购买 nike

我正在寻找替换/删除给定字符串中的所有换行符,但嵌套在 <pre> 中的换行符除外。标签。所以对于以下字符串:

var text = @"
Some contents which is formatted
over multiple
lines but contains a
<pre>
tag which has
also has
multiple line breaks.
</pre>
";

我想删除所有换行符,除了嵌套在 pre 标记中的换行符:

Regex.Replace(text, "\n", "<br />");

最佳答案

使用负面展望,您仍然可以在一行中完成:

text = Regex.Replace(text, "\n(?![^<]*</pre>)", "<br />");

这是一些测试代码,更好的示例包含多个 <pre>标签:

var text = @"
Some contents which is formatted
over multiple
lines but contains a
<pre>
tag which has
also has
multiple line breaks.
</pre>
foo 1
bar 1
<pre>
tag which has
also has
multiple line breaks.
</pre>
foo 2
bar 2
";
text = Regex.Replace(text, "\n(?![^<]*</pre>)", "<br />");
Console.WriteLine(text);

输出:

<br />    Some contents which is formatted<br />    over multiple<br />    lines but contains a <br />    <pre>
tag which has
also has
multiple line breaks.
</pre><br /> foo 1<br /> bar 1<br /> <pre>
tag which has
also has
multiple line breaks.
</pre><br /> foo 2<br /> bar 2<br />

关于c# - 替换 <pre> 标签之间的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188203/

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