gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:25:17 25 4
gpt4 key购买 nike

我正在尝试从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com