簡體   English   中英

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替換命令它工作: cat tmp.html | perl -pe 's/<script.*?>[\\s\\S]*?< *?\\/ *?script *?>//g' 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>

PS我正在使用正則表達式解析HTML,因為當頁面上有復雜的腳本時,我被迫使用的HTML解析器(xmlpath)會中斷。 我正在使用此正則表達式從頁面中刪除腳本,然后將其傳遞給解析器。

你需要告訴perl不要將文件的每一行拆分成它自己的單獨記錄-0

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

這實際上告訴perl打破'\\0'上的記錄。 perl -0777將非常明確地perl -0777整個文件。

順便說一句,因為我發現整個文件都令人討厭,而且因為我不關心html對於換行的說法... 如果你能保證沒有重要的內容,那么更快,更清潔,更正確的方法在<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 "$1\n" if /(.+)<script>/;print "$1\n" if /<\/script>(.+)/;' example.html
<important1/>
<edgecase1/>
<edgecase2/>
<important2/>
<important3/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM