Regex to Parse Hyperlinks and Descriptions

前端 未结 6 1769
长情又很酷
长情又很酷 2020-12-11 07:20

C#: What is a good Regex to parse hyperlinks and their description?

Please consider case insensitivity, white-space and use of single quotes (instead of double quote

相关标签:
6条回答
  • 2020-12-11 08:09

    I found this but apparently these guys had some problems with it.

    Edit: (It works!)
    I have now done my own testing and found that it works, I don't know C# so I can't give you a C# answer but I do know PHP and here's the matches array I got back from running it on this:

    <a href="pages/index.php" title="the title">Text</a>
    
    array(3) { [0]=> string(52) "Text" [1]=> string(15) "pages/index.php" [2]=> string(4) "Text" } 
    
    0 讨论(0)
  • 2020-12-11 08:14

    See this example from StackOverflow: Regular expression for parsing links from a webpage?

    Using The HTML Agility Pack you can parse the html, and extract details using the semantics of the HTML, instead of a broken regex.

    0 讨论(0)
  • 2020-12-11 08:19

    I have a regex that handles most cases, though I believe it does match HTML within a multiline comment.

    It's written using the .NET syntax, but should be easily translatable.

    0 讨论(0)
  • 2020-12-11 08:19

    Here is a regular expression that will match the balanced tags.

    (?:""'[""'].*?>)(?(?>(?)|(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:)

    0 讨论(0)
  • 2020-12-11 08:21

    As long as there are no nested tags (and no line breaks), the following variant works well:

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

    As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g. .NET regular expressions use a stack; I found this:

    (?:<a.*?href=[""'](?<url>.*?)[""'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>) 
    

    Source: http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx

    0 讨论(0)
  • 2020-12-11 08:22

    Just going to throw this snippet out there now that I have it working..this is a less greedy version of one suggested earlier. The original wouldnt work if the input had multiple hyperlinks. This code below will allow you to loop through all the hyperlinks:

    static Regex rHref = new Regex(@"<a.*?href=[""'](?<url>[^""^']+[.]*?)[""'].*?>(?<keywords>[^<]+[.]*?)</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    public void ParseHyperlinks(string html)
    {
       MatchCollection mcHref = rHref.Matches(html);
    
       foreach (Match m in mcHref)
          AddKeywordLink(m.Groups["keywords"].Value, m.Groups["url"].Value);
    }
    
    0 讨论(0)
提交回复
热议问题