正则表达式在HTML中捕获多行脚本标记 [英] regex catching multiline script tag inside html

查看:93
本文介绍了正则表达式在HTML中捕获多行脚本标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取html页面中的内联脚本标签. 正则表达式最终将由c#驱动. 现在,我正在使用Expresso进行测试.

I need to grab inline script tags inside html pages. The regex will eventually be driven from c#. Now I am using Expresso for test purpose.

以下是目前最好的方法:

The following is the best for now:

.*<script.*\r\n(.*\r\n)*\s*</script>

  • .*<script捕获脚本标记
  • .*\r\n捕获任何内容直到行尾
  • (.*\r\n)*捕获脚本的其他行
  • \s*</script>捕获结束脚本,并在
  • 之前加上任何缩进
  • .*<script catch the script tag
  • .*\r\n catch anything till the end of line
  • (.*\r\n)* catch other lines of the script
  • \s*</script> catch the closing script, with any indentation before

它捕获第一个标签之间的所有内容,包括html和其他脚本标签.

It grabs ALL the stuff between the first tag, inculding html and other script tags.

推荐答案

同一行上的两个脚本会破坏您的正则表达式.尝试在页面源中输入您的问题.

Two scripts on the same line will break your regex. Try it on the source of the page with your question.

使用正则表达式解析HTML并不是一个好主意(在您的问题的注释中有一个链接,其中

Parsing HTML with regex is not a very good idea (there is a link in the comment to your question which answers why the <center> cannot hold); use HTML parser instead.

下一个代码段通过使用 HtmlAgilityPack 来选择<script>节点:

The next code snippet selects the <script> nodes by using HtmlAgilityPack:

var doc = new HtmlDocument();
doc.Load(html);
var scripts = doc.DocumentNode.SelectNodes("//script");

这不是比正则表达式简单吗?

Isn't this is simplier than regex?

这篇关于正则表达式在HTML中捕获多行脚本标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆