【问题标题】:Replace line breaks except inside <pre> tags with brackets(<>) inside <pre> tags将 <pre> 标签内的换行符替换为 <pre> 标签内的括号(<>)
【发布时间】:2018-07-25 04:20:44
【问题描述】:

我使用question 中提供的答案替换了 pre 标记之外的所有换行符。

\n(?![^<]*<\/pre>)

在 pre 标记中的内容有 括号之前它工作正常。

例如,输入:

<p>Test contennt for regex
with line breaks</p>
<pre>code block 
with multi line content
working fine</pre>
<pre class="brush:C#">
test line break before 
open paranthesis < is not working fine
line breaks after paranthesis
is accepted
</pre>

输出是

<p>Test contennt for regexwith line breaks</p><pre>code block 
with multi line content
working fine</pre><pre class="brush:C#">test line break before open paranthesis < is not working fine
line breaks after paranthesis
is accepted
</pre>

这是不正确的 - 并非所有换行符都被删除。

this regex101

【问题讨论】:

标签: regex regex-negation regex-greedy


【解决方案1】:

试试这个:

/\n(?=((?!<\/pre).)*?(<pre|$))/sg

我们的想法是有一个很大的前瞻性。

((?!<\/pre).)*?

重复匹配任何字符(包括带有. 的换行符),然后是

(<pre|$)

要求上述字符不是&lt;/pre 中的&lt;。然后,匹配&lt;pre(表示原始换行符不是&lt;pre内,或者匹配文件的结尾。

https://regex101.com/r/cjZQO9/2

输入

<p>Test contennt for regex
with line breaks</p>
<pre>code block 
with multi line content
working fine</pre>
text
more text
<pre class="brush:C#">
test line break before 
open paranthesis < is not working fine
line breaks after paranthesis
is accepted
</pre>
text

输出是

<p>Test contennt for regexwith line breaks</p><pre>code block 
with multi line content
working fine</pre>textmore text<pre class="brush:C#">
test line break before 
open paranthesis < is not working fine
line breaks after paranthesis
is accepted
</pre>text

【讨论】:

  • 作品有魅力。竖起大拇指。
【解决方案2】:

如果使用 pcre 你也可以(*SKIP) 标签

/<pre.*?<\/pre>(*SKIP)(*F)|\n/s

See a demo at regex101

【讨论】:

    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 2013-03-09
    • 2016-12-17
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多