簡體   English   中英

正則表達式,用於匹配包含特定字符串的腳本標簽

[英]Regex for matching script tags that contain a specific string

在Node.js中,我試圖從HTML文件中提取特定的腳本標簽。 該文件具有許多腳本標記,但是只有其中一些包含push()方法調用。 我只想匹配那些。 我已經鏈接了一個非常簡化的Regexr示例。 我需要這不與前三行匹配,盡管這是第一場比賽的一部分。

當前正則表達式: <script\\b[^>]*>([\\n\\r\\s\\S]*?)push([\\n\\r\\s\\S]*?)<\\/script>

示例: https//regexr.com/3qqt8

聽起來像是清潔工作。 我建議在現有代碼的基礎上,捕獲並忽略腳本塊,而無需交替輸入推鍵關鍵字,然后只使用捕獲組中存儲的值即可。 可能看起來像這樣:

<script\b[^>]*>(?:(?!push)[\s\S])*?<\/script>|<script\b[^>]*>([\s\S]*?)push([\s\S]*?)<\/script>

演示版

您可能希望使用更強的關鍵字定義,例如\\.push\\(以避免誤報。

 var regex = /<skript\\b[^>]*>(?:(?!push)[\\s\\S])*?<\\/skript>|<skript\\b[^>]*>([\\s\\S]*?)push([\\s\\S]*?)<\\/skript>/g; var str = `<skript> function() {} </skript> <div></div> <skript> someFuncCall(); array.push(); </skript> <skript> otherFuncCall(); array.push(); </skript> `; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } if(m[1] && m[2]) // if group 1 & 2 exists console.log(`Found: ${m[1]}push${m[2]}`); } 

PS:看起來腳本標簽已在摘要中過濾掉,因此我已將它們替換為skript -tags。

暫無
暫無

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

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