c# - 用于查找 iframe 标记和检索属性的正则表达式

标签 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 属性的顺序不同,则此正则表达式将不起作用。

有什么方法可以修改此正则表达式以忽略属性顺序并返回分组在 Matches 中的 iframe 以便我可以遍历它们?

最佳答案

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

(?<=<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

关于c# - 用于查找 iframe 标记和检索属性的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29893444/

相关文章:

c# - 使用加密文件的应用程序复制保护

c# - Visual Studio 构建失败 : unable to copy exe-file from obj\debug to bin\debug

c# - 如何将列表数组与 GridView 或 DataList 绑定(bind)?

c# - 打开 rdlc 报告时在报告查看器中手动设置值

c# - 在队列中播放 .wav 文件

c# - Bot Framework : Enable PromptDialog. Cortana 说出的文本

.net - 什么会导致项目突然忘记其中一个引用?

Linux 文件权限的正则表达式(数字符号)

javascript - 正则表达式匹配其中不含短语的短语

regex - 如何缓存和使用 perl6 语法中缓存的正则表达式?