Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string rawString = link;
foreach (Match m in linkParser.Matches(rawString))
{
string links = m.Value;
}我正在尝试解析/获取此字符串中的链接:
<a href="http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1"><b>我只想得到这一部分:
http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1但是我在字符串链接中得到的是:
http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1"><b最后剩下的是">
发布于 2014-07-04 20:04:24
尝试将\S+更改为[^\"\>]+
最后一个字符串:\b(?:https?:\/\/|www\.)[^\"\>]+\b
但这不仅仅是找到工作链接。如果你的链接类似于<a href="www.a<not working Link>flupp"><b>,它会找到www.a<not working Link。
这个表达式只查找直到下一个"或>的所有内容(如果它是一个有效的HTML,并且您知道两个引号之间的文本是一个普通链接,那么您只需要" (这将使表达式成为\b(?:https?:\/\/|www\.)[^\"]+\b))。
使用它,它将找到www.a<not working Link>flupp,这正是两个引号之间的内容。
如果你想禁止更多的字符,你必须编辑[^\"\>]+。
顺便说一句:我认为在?:https?:之后同时避开两个/是有意义的
这样做的原因是因为您告诉他查找所有非空格字符,并且应该以字母结尾。因为这个表达式是贪婪的,所以它会“吃”尽可能多的非空格字符。"和>不是空格字符,(制表符)是。[^\"]+告诉他在找到"之前获取所有字符。在找到一个后,他会停下来。
发布于 2014-07-04 21:16:59
我发现像一些人说的那样使用HTMLAgilityPack,因为它不是一种常规的语言。下载后,考虑到这是源代码中唯一包含此文本的节点:
HtmlAgilityPack.HtmlDocument hp = new HtmlAgilityPack.HtmlDocument();
string source = File.ReadAllText( @"C:\Users\Admin\Desktop\source.txt" );
hp.LoadHtml(source);
var node = hp.DocumentNode.SelectSingleNode("//a[contains(@href, 'http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1')]");
string found = node.Attributes["href"].Value;
Console.WriteLine(found);你可以从任何你想要的地方拉你的源代码,无论是通过网络客户端或本地文件下载。这将返回:http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1
https://stackoverflow.com/questions/24573471
复制相似问题