替换换行符,除了< pre>之间的换行符.标签 [英] Replace line breaks except for ones between <pre> tags

查看:54
本文介绍了替换换行符,除了< pre>之间的换行符.标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望替换/删除给定字符串中的所有换行符,嵌套在< pre> 标记中的换行符除外.因此,对于以下字符串:

I'm looking to replace/remove all line breaks within a given string except for ones nested within a <pre> tag. So for the following string:

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

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

I would like to remove all line breaks except for ones nested within a pre tag:

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

推荐答案

使用否定的外观,您仍然可以在一行中做到这一点:

Use a negative look ahead and you can still do it in one line:

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

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

Here's some test code, with a better sample containing multiple <pre> tags:

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 />  

这篇关于替换换行符,除了&lt; pre&gt;之间的换行符.标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆