将 <pre> 标签内的换行符替换为 <pre> 标签内的方括号 (<>)

Replace line breaks except inside <pre> tags with brackets(<>) inside <pre> tags

我使用 question.

中可用的答案替换了前置标签外的所有换行符
\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

试试这个:

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

这个想法是要有一个大的前瞻性。

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

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

(<pre|$)

要求上述字符不是</pre中的<。然后,匹配 <pre(表示原始换行符在 <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

如果使用 pcre,您还可以 (*SKIP) 标签

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

See a demo at regex101