首页 > 解决方案 > 用于匹配包含特定字符串的脚本标签的正则表达式

问题描述

在 Node.js 中,我试图从 HTML 文件中提取特定的脚本标签。该文件有许多脚本标签,但其中只有一些包含 push() 方法调用。我只想匹配那些。我已经链接了一个非常简化的示例 Regexr,它很接近。我需要这个不匹配前三行作为第一场比赛的一部分。

当前的正则表达式:<script\b[^>]*>([\n\r\s\S]*?)push([\n\r\s\S]*?)<\/script>

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

标签: javascriptnode.jsregex

解决方案


听起来像是清洁工作。在您现有代码的基础上,我建议捕获并忽略不带 push-keyword 的脚本块,然后只使用存储在捕获组中的值。这可能看起来像这样:

<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:看起来 script-tags 在片段中被过滤掉了,因此我用skript -tags 替换了它们。


推荐阅读