C#从iframe html标记中获取src
本文关键字:获取 src iframe html | 更新日期: 2023-09-27 17:59:54
基本上我有一个用户创建的字符串,它可能有也可能没有youtube的iframe链接。由于这是一个客户端应用程序,它不使用html标签,我有一种特殊的形式来显示youtube视频。然而,我需要从标记中获取src,并将其周围的所有数据都不替换。它也可能有多个链接,所以这需要像regex一样在全局范围内完成。。
示例:用户字符串:
<iframe width='300px' height='225px' src='http://www.youtube-nocookie.com/embed/4FhG-UYRHJ0' frameborder='0' allowfullscreen></iframe>
我想要输出的内容:我希望用户只看到:http://www.youtube-nocookie.com/embed/4FhG-UYRHJ0
,然后我可以处理其余的。
任何帮助都非常感谢,因为我甚至不知道如何开始。谢谢大家。
您也可以使用此
string iframe = "<iframe width='300px' height='225px' src='http://www.youtube-nocookie.com/embed/4FhG-UYRHJ0' frameborder='0' allowfullscreen></iframe>";
Match matchdec = Regex.Match(iframe, @"'ssrc=''b('S*)'b", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
if (matchdec.Success)
{
if (matchdec.Groups.Count > 1)
{
string retval = matchdec.Groups[1].Value;
}
}
对于所有匹配,您可以使用:-
string iframe = "<iframe width='300px' height='225px' src='http://www.youtube-nocookie.com/embed/4FhG-UYRHJ0' frameborder='0' allowfullscreen></iframe>";
iframe += "<iframe width='300px' height='225px' src='http://www.youtube-nocookie.com/embed/newid' frameborder='0' allowfullscreen></iframe>";
Match matchdec = Regex.Match(iframe, @"'ssrc=''b('S*)'b", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
while (matchdec.Success)
{
if (matchdec.Groups.Count > 1)
{
string retval = matchdec.Groups[1].Value;
}
matchdec = matchdec.NextMatch();
}
更换添加此行
iframe = Regex.Replace(iframe, retval, "yournewurl");
希望这能有所帮助。
这里有一个正则表达式可以帮助您开始:
(?<=src=')[^']+
注意:可能是一些未考虑的边缘情况。我将把它作为OP的练习:)
您可以使用以下代码;
var source = Regex.Match(iframeStr, "<iframe.+?src=['"'](.+?)['"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;