正则表达式找到iframe标签和检索属性

时间:2015-04-27 10:41:21

标签: c# .net regex

我正在尝试从HTML输入中检索iframe标记和属性。

示例输入

<div class="1"><iframe width="100%" height="427px" src="https://www.youtube.com/embed/1" frameborder="0" allowfullscreen=""></iframe></div>
<div class="2"><iframe width="100%" height="427px" src="https://www.youtube.com/embed/2" frameborder="0" allowfullscreen=""></iframe></div>

我一直在尝试使用以下正则表达式来收集它们:

<iframe.+?width=[\"'](?<width>.*?)[\"']?height=[\"'](?<height>.*?)[\"']?src=[\"'](?<src>.*?)[\"'].+?>

这导致

enter image description here

这正是我想要的格式。

问题是,如果HTML属性的顺序不同,那么这个正则表达式就不会起作用。

有没有办法修改此正则表达式以忽略属性顺序并返回iframe中分组的Matches以便我可以迭代它们?

5 个答案:

答案 0 :(得分:3)

正则表达式匹配模式,字符串的结构定义了要使用的模式,因此,如果要使用正则表达式,则顺序很重要。

您可以通过两种方式处理此问题:

  1. 良好推荐方式是使用正则表达式(mandatory link)解析HTML,而是使用解析框架,例如HTML Agility Pack。这应该允许您处理所需的HTML并提取您所追求的任何值。

  2. 第二种,糟糕,不推荐的方式这样做是为了将你的匹配分成两部分。您首先使用类似的内容:<iframe(.+?)></iframe>来提取整个 iframe decleration,然后使用多个较小的正则表达式来查找并找到您之后的设置。如果您的iframe结构如下,则上述正则表达式显然会失败:<iframe.../>。这应该给你一个关于为什么你不应该通过正则表达式进行HTMl解析的提示。

  3. 如上所述,您应该选择第一个选项。

答案 1 :(得分:3)

这是一个将忽略属性顺序的正则表达式:

(?<=<iframe[^>]*?)(?:\s*width=["'](?<width>[^"']+)["']|\s*height=["'](?<height>[^'"]+)["']|\s*src=["'](?<src>[^'"]+["']))+[^>]*?>

RegexStorm demo

C#示例代码:

var rx = new Regex(@"(?<=<iframe[^>]*?)(?:\s*width=[""'](?<width>[^""']+)[""']|\s*height=[""'](?<height>[^'""]+)[""']|\s*src=[""'](?<src>[^'""]+[""']))+[^>]*?>");
var input = @"YOUR INPUT STRING";
var matches = rx.Matches(input).Cast<Match>().ToList();

输出:

enter image description here

答案 2 :(得分:1)

您需要使用OR运算符(|)。请参阅下面的更改

 sqlservice.getAllCases().then(function(data) {
   console.log(data);
   $scope.items = [];
   for (var i = 0; i < data.length; i++)
     $scope.items.push(data[i]);
   console.log($scope.items);
 })

答案 3 :(得分:1)

您可以使用此正则表达式

<iframe[ ]+(([a-z]+) *= *['"]*([a-zA-Z0-9\/:\.%]*)['"]*[ ]*)*>

它递归匹配每个'name'='value'对并在匹配中以相同的顺序存储它,您可以遍历mathes以顺序获取名称和值。适合大多数字符值,但如果需要,您可以添加更多字符。

答案 4 :(得分:1)

使用Html Agility Pack(通过nuget获得):

using System;
using HtmlAgilityPack;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.Load("HTMLPage1.html"); //or .LoadHtml(/*contentstring*/);

            HtmlNodeCollection iframes = doc.DocumentNode.SelectNodes("//iframe");

            foreach (HtmlNode iframe in iframes)
            {
                Console.WriteLine(iframe.GetAttributeValue("width","null"));
                Console.WriteLine(iframe.GetAttributeValue("height", "null"));
                Console.WriteLine(iframe.GetAttributeValue("src","null"));
            }

        }
    }
}
相关问题