繁体   English   中英

如何从 C# 中的字符串中提取 url

[英]How to extract an url from a String in C#

我有这个字符串:

 "<figure><img
 src='http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg'
 href='JavaScript:void(0);' onclick='return takeImg(this)'
 tabindex='1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>"

如何检索此链接:

http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg

所有字符串都是相同的类型,所以我需要在src=href之间获取子字符串。 但我不知道该怎么做。 谢谢。

如果您解析 HTML,请不要使用字符串方法,而是使用真正的 HTML 解析器,例如HtmlAgilityPack

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);  // html is your string
var linksAndImages = doc.DocumentNode.SelectNodes("//a/@href | //img/@src");
var allSrcList = linksAndImages
    .Select(node => node.GetAttributeValue("src", "[src not found]"))
    .ToList();

您可以使用正则表达式:

var src = Regex.Match("the string", "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;

通常,在解析 HTML 代码中的值时,您应该使用 HTML/XML 解析器,但是对于像这样的有限字符串,Regex 就可以了。

string url = Regex.Match(htmlString, @"src='(.*?)'").Groups[1].Value;

如果您的字符串始终采用相同的格式,您可以轻松地这样做:

string input =  "<figure><img src='http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg' href='JavaScript:void(0);' onclick='return takeImg(this)' tabindex='1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
// link is between ' signs starting from the first ' sign so you can do :
input = input.Substring(input.IndexOf("'")).Substring(input.IndexOf("'"));
// now your string looks like : "http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg"

return input;
string str = "<figure><imgsrc = 'http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg'href = 'JavaScript:void(0);' onclick = 'return takeImg(this)'tabindex = '1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";

int pFrom = str.IndexOf("src = '") + "src = '".Length;
int pTo = str.LastIndexOf("'href");

string url = str.Substring(pFrom, pTo - pFrom);

来源 :

获取字符串中两个字符串之间的字符串

在这种情况下,Q 是您的字符串,我查找您想要的属性的索引 (src = '),然后删除前几个字符(包括空格在内的 7 个),然后您通过查找 ' 来查找文本何时结束。

通过删除前几个字符,您可以使用 .IndexOf 来查找要删除的字符数,因此它不是硬编码的。

        string q =
            "<figure><img src = 'http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg' href = 'JavaScript:void(0);' onclick = 'return takeImg(this)'" +
            "tabindex = '1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
        string z = q.Substring(q.IndexOf("src = '"));
        z = z.Substring(7);
        z = z.Substring(0, z.IndexOf("'"));
        MessageBox.Show(z);

这当然不是最优雅的方式(请查看其他答案:))。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM