Perl 正则表达式在在线 PCRE 测试器中工作,但在 perl 命令中不工作

Perl regex working in online PCRE tester but not in perl command

我编写了以下 PCRE 正则表达式以从 HTML 页中删除脚本:<script.*?>[\s\S]*?< *?\/ *?script *?>

它适用于许多在线 PCRE 正则表达式测试器:

https://regex101.com/r/lsxyI6/1

https://www.regextester.com/?fam=102647

当我在 bash 终端中 运行 以下 perl 替换命令时 NOT 工作:cat tmp.html | perl -pe 's/<script.*?>[\s\S]*?< *?\/ *?script *?>//g'

我正在使用以下测试数据:

<script>
                       $(document).ready(function() {
                           var url = window.location.href;
                           var element = $('ul.nav a').filter(function() {
                               if (url.charAt(url.length - 1) == '/') {
                                   url = url.substring(0, url.length - 1);
                               }

                               return this.href == url;
                           }).parent();

                           if (element.is('li')) {
                               element.addClass('active');
                           }
                       });
                   </script>

P.S. 我正在使用正则表达式来解析 HTML 因为我被迫使用的 HTML 解析器 (xmlpath) 在以下情况下中断页面上有复杂的脚本。我正在使用此正则表达式从页面中删除脚本,然后再将其传递给解析器。

你需要用 -0 告诉 perl 不要将文件的每一行分解成自己单独的记录。

 perl -0 -pe 's/<script.*?>[\s\S]*?< *?\/ *?script *?>//g' tmp.html

这实际上告诉 perl 在 '[=12=]' 上分解记录。 perl -0777 将非常明确地吞噬整个文件。

顺便说一句,因为我觉得吞噬整个文件令人反感,而且因为我不在乎 html 对换行符的看法...更快、更清晰、更正确的方法IF 你可以保证 <script> 标记行上没有重要内容是:

perl -ne 'print if !(/<script>/../<\/script>/)' tmp.html

(当然,根据您的喜好修改两个正则表达式) .. 是一个状态运算符,它在表达式为真之前被表达式打开,在表达式为真之后被表达式关闭。

~/test£ cat example.html
<important1/>
<edgecase1/><script></script><edgecase2/>
<important2/>
<script></script>
<important3/>
<script>
<notimportant/>
</script>

~/test£ perl -ne 'print if !(/<script>/../<\/script>/)' example.html
<important1/>
<important2/>
<important3/>

并(主要)解决脚本标记行上但标记之外的内容:

~/test£ perl -ne 'print if !(/<script>/../<\/script>/);print "\n" if /(.+)<script>/;print "\n" if /<\/script>(.+)/;' example.html
<important1/>
<edgecase1/>
<edgecase2/>
<important2/>
<important3/>