正则表达式查找超链接的查询字符串部分

时间:2009-09-22 06:53:48

标签: .net regex

我对正则表达式很陌生,但我确信正则表达式会给我一些比使用字符串方法更优雅的东西。

我有一个以下形式的超链接:

<a href="http://server.com/default.aspx?abc=123">hello</a>

我想把查询字符串部分拉出来。另外,对于.net正则表达式(羞怯的笑)有什么好的参考?我发现MSDN reference非常难以理解。

6 个答案:

答案 0 :(得分:2)

以下代码将提取查询字符串

string html = "<a href=\"http://server.com/default.aspx?abc=123\">hello</a>";
Match m = Regex.Match(html, "<a[^>]+href=\".*?\\?(.*?)\">");
string querystring = m.Groups[1].ToString();

正则表达式解释说:

take only strings starting with <a href="
between the a and href there can be other attributes, spaces, it ignores them
make a group of the the url, from the first question mark to the ending quotes - this is your query string

答案 1 :(得分:1)

对于正则表达式开发,我建议Expresso。至于正则表达式本身,搜索?并匹配到下一个“。

答案 2 :(得分:1)

 /<a\s+href="[^?]+\?(.*)">/

甚至这应该有效:

/\?(.+)"/

编辑:了解贪婪..对于懒惰(如果有其他属性),请使用此。

/\?(.+?)"/

谢谢@Guffa

答案 3 :(得分:1)

而不是正则表达式,你不能只使用Uri类,特别是Uri.Query属性吗?

示例:

Uri uri = new Uri("http://server.com/default.aspx?abc=123");
Console.WriteLine(uri.Query);

打印:

  

?abc=123

答案 4 :(得分:0)

也许是简单的事情?

/\?([^\"]+)\"/

匹配abc=123

答案 5 :(得分:0)

这个正则表达式应该可行

(?<=href="[^"]+\?)[^"]+

Here it is with test cases in Regex Hero。 (您也可以使用此工具为您生成.NET代码。)

至于参考,我正在做一个干净的&amp; amp;简明.NET regex reference。它还没有完成,但它非常接近。您还可以单击正则表达式以查看带有简洁jQuery动画的示例向下滑动,但我离题了。

然后在http://www.regular-expressions.info/有一个更详细的参考网站,有快速参考和叙述风格来解释一切。