正则表达式在 HTML JavaScript 标签中查找注释

时间:2021-07-20 20:18:44

标签: javascript html regex

如果任何精通正则表达式的人可以提供帮助,我们将不胜感激。我正在尝试使用以下正则表达式(请参阅 URL)来查找脚本标记中的所有 HTML JavaScript 注释。这将使用 Windows PowerShell 运行所需的任务。

下面的例子是我目前所拥有的。但是,它仍然没有:

(?s)(?(?=\A).*?<script[^>]*>).*?(?:\K\/\/|<\/script>.*?(?:<script[^>]*>|\z)(*SKIP)(*FAIL))
  • 应该突出显示“//”右侧的所有文本,直到换行
  • 不应在脚本标签内包含网址
  • 脚本标签不应该区分大小写

示例 URL 还包括七个测试场景: https://regex101.com/r/YpCJXM/1

目标: 如果每个场景都可以突出显示注释文本,同时不包括脚本标记之外的任何额外区域。只要它适用于 regex101 我就可以让它与 PS 一起使用!

编辑:我完全知道你不应该用正则表达式解析它!不过,我相信精通正则表达式的人只需完成此任务所需的少数场景即可轻松应对。

Edit_2: 下面是另一个例子。但是,它仍然没有:

(\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*)
  • 应该只在脚本标签内包含文本

答案: 以下是 MikeM 的回答的轻微变化,以允许 http 或 https

(?si)(?<!http:|https:)\/\/[^\r\n]*(?=(?:(?!<script[^>]*>).)*<\/script>)

1 个答案:

答案 0 :(得分:1)

以下内容并非万无一失,但它通过了您的测试:

(?si)(?<!https:)\/\/[^\r\n]*(?=(?:(?!<script[^>]*>).)*<\/script>)

正向前瞻确保结束脚本标签出现在开始脚本标签之前,在字符串的前面。

示例用法:

$pattern = '(?si)(?<!https?:)\/\/[^\r\n]*(?=(?:(?!<script[^>]*>).)*<\/script>)'
$results = $data | Select-String $pattern -AllMatches
$results.Matches.Value

// find this comment here
//find this comment here
//find this comment here
// find this comment here
// find this comment here
//find this comment here
// find this comment here
//find this comment here
//find this comment here with this included also!
相关问题