用于匹配包含特定字符串的脚本标记的正则表达式

时间:2018-06-11 01:00:23

标签: javascript node.js regex

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

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

实施例: https://regexr.com/3qqt8

1 个答案:

答案 0 :(得分:0)

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

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

Demo

您可能希望使用更强大的关键字定义,例如: \.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替换了它们。

相关问题