如何使用正则表达式从html字符串中提取Web地址

时间:2012-02-24 10:29:49

标签: c# regex

我需要从这个字符串中提取网址:

<p> Feb 24 - <a href="http://austin.daylife.org/apa/2867907745.html">$390 / 2br - 600ft&sup2; - Sleeps 4-Walk to SXSW-SOCO-Perfect Location</a> - <font size="-1"> (South 5th)</font> <span class="p"> pic</span></p>

如何在C#中使用正则表达式实现相同的目标?

2 个答案:

答案 0 :(得分:1)

使用此正则表达式:

http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&amp;\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?

编辑:更简单的表达方式:

http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?

答案 1 :(得分:1)

这对我有用:

        string source = " <p> Feb 24 - <a href=\"http://austin.daylife.org/apa/2867907745.html\">$390 / 2br - 600ft&sup2; - Sleeps 4-Walk to SXSW-SOCO-Perfect Location</a> - <font size=\"-1\"> (South 5th)</font> <span class=\"p\"> pic</span></p> ";
        Regex regex = new Regex("<a[^>]*? href=\"(?<url>[^\"]+)\"[^>]*?>(?<text>.*?)</a>");
        var m = regex.Match(source);
        string url = m.Groups["url"];