javascript - 用于匹配包含特定字符串的脚本标签的正则表达式
问题描述
在 Node.js 中,我试图从 HTML 文件中提取特定的脚本标签。该文件有许多脚本标签,但其中只有一些包含 push() 方法调用。我只想匹配那些。我已经链接了一个非常简化的示例 Regexr,它很接近。我需要这个不匹配前三行作为第一场比赛的一部分。
当前的正则表达式:<script\b[^>]*>([\n\r\s\S]*?)push([\n\r\s\S]*?)<\/script>
解决方案
听起来像是清洁工作。在您现有代码的基础上,我建议捕获并忽略不带 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 替换了它们。
推荐阅读
- sql - 查询中的多值选择 PrestoDB
- sql - 如何在没有任何数据集的情况下在 2 个日期(例如分钟)之间进行 SELECT
- c++ - 是否有可用于转换单位的 C++ 预处理器指令或类似指令
- powerapps - 如何在 PowerApp 中读取环境变量?
- javascript - 如何使用 DYMO Connect for Desktop 为标签生成 XML 以在 Javascript 中打印
- python - 如何使用索引标签将 DataFrame 分组并执行操作以根据每个索引在特定列中找到 3 个最大的
- google-cloud-platform - 当我将 csv 文件推送到存储桶但将空值插入 bigquery 表时,云函数被触发
- java - FileNotFoundException 但文件出现在正确的路径
- c# - 当我在邮递员中传递 URL 时,调试器没有来到控制器给出错误?
- javascript - 将信息从表单传递到函数 React js