Regex: markdown-style link matching

Posted by The.Anti.9 on Stack Overflow See other posts from Stack Overflow or by The.Anti.9
Published on 2010-05-24T05:22:38Z Indexed on 2010/05/24 5:31 UTC
Read the original article Hit count: 462

Filed under:
|
|

I want to parse markdown style links, but I'm having some trouble matching the reference style ones. Like this one: [id]: http://example.com/ "Optional Title Here"

My regex gets the id and the url, but not the title.

Heres what I have:

/\[([a-zA-Z0-9_-]+)\]: (\S+)\s?("".*?"")?/

I go through and add the references to a hashtable. the id as the key and the value is an instance of a class I made called LinkReference that just contains the url and the title. In case the problem is not my regex, and my code adding the matches to the hash table, Heres my code for that too:

        Regex rx = new Regex(@"\[([a-zA-Z0-9_-]+)\]: (\S+)\s?("".*?"")?");
        MatchCollection matches = rx.Matches(InputText);
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            string title = null;
            try
            {
                title = groups[3].Value;
            }
            catch (Exception)
            {
                // keep title null
            }
            LinkReferences.Add(groups[1].Value, new LinkReference(groups[2].Value, title));
        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex