Search code examples
asp.netregexflickr

How to write regex to extract FlickR Image ID From URL?


I'm looking to do do two things, and I am looking to do them in a beautiful way. I am working on a project that allows users to upload flickr photos by simply entering their flickr image URL. Ex: http://www.flickr.com/photos/xdjio/226228060/

I need to:

  • make sure it is a URL that matches the following format: http://www.flickr.com/photos/[0]/[1]/

  • extract the following part: http://www.flickr.com/photos/xdjio/[0]/

Now I could very easily write some string methods to do the above but I think it would be messy and love learning how to do these things in regex. Although not being a regex ninja I am currently unable to do the above.


Solution

  • Given an input string with a URL like the one you provided, this will extract the image ID for any arbitrary user:

    string input = "http://www.flickr.com/photos/xdjio/226228060/";
    Match match = Regex.Match(input, "photos/[^/]+/(?<img>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.SingleLine);
    if(match.Success)
    {
        string imageID = match.Groups["img"].Value;
    }
    

    Breaking it down, we are searching for "photos/" followed by one or more characters that is not a '/', followed by a /, followed by one or more characters that are numbers. We also put the numbers segment into a named group called "img".