使用regex查找两个输入字符串之间的内容
本文关键字:字符串 输入 之间 两个 查找 regex 使用 | 更新日期: 2023-09-27 17:59:53
我正在开发一个简单的facebook信使客户端(不需要开发人员帐户),到目前为止,我所实现的是获取所有消息-名称、预览、时间。我想找到的是用户href链接
到目前为止,我有这个:
MatchCollection name = Regex.Matches(
htmlText, "<div class='"_l2'">(.*?)</div>");
MatchCollection preview = Regex.Matches(
htmlText, "<div class='"_l3 fsm fwn fcg'">(.*?)</div>");
MatchCollection time = Regex.Matches(
htmlText, "<div class='"_l4'">(.*?)</div>");
它完全起作用。
但我尝试了一些我在这个网站上找到的东西,但似乎都不起作用。href类似于:<a class="_k_ hoverZoomLink" rel="ignore" href="
并以"结尾。有人能给我推荐一篇文章吗?这篇文章实际上可能会帮助我知道如何获得href。或者甚至是一种比regex更好的方法,但我真的更喜欢regex:
for (int i = 0; i < name.Count; i++)
{
String resultName = Regex.Replace(name[i].Value, @"<[^>]*>", String.Empty);
String newName = resultName.Substring(0, resultName.Length - 5);
String resultPreview = Regex.Replace(preview[i].Value, @"<[^>]*>", String.Empty);
String s = time[i].Value;
int start = s.IndexOf("data-utime='"") + 28;
int end = s.IndexOf("</abbr>", start);
String newTime = s.Substring(start, (end - start));
threads.Add(new Thread(newName, resultPreview, newTime, ""));
}
提前感谢。
使用真正的html解析器,如HtmlAgilityPack
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlstring);
var link = doc.DocumentNode.SelectSingleNode("//a[@class='_k_ hoverZoomLink']")
.Attributes["href"].Value;
代替XPath,您也可以使用Linq
var link = doc.DocumentNode.Descendants("a")
.Where(a => a.Attributes["class"] != null)
.First(a => a.Attributes["class"].Value == "_k_ hoverZoomLink")
.Attributes["href"].Value;