Retrieving a Flickr Photo ID from a URL using RegEx


While working on a recent Flickr/Google Maps mashup i needed to make it as simple for users to share their Flickr photos as possible. What is easier than simply asking them to enter the Flickr photo page URL? Using this I'll show you a simple way to use RegEx to retrieve the photo ID part of the URL using c# as well as a JavaScript RegEx version for your ASP.Net RegEx validators. Lets get to it!

logo_home.png.v2 So there is two parts to this post: The code used to retrieve the Flickr image ID from the photo page URL as well as the JavaScript version to simply check to see that the user has entered a valid Flickr photo page URL without having to postback.

Spoiler Alert

If you are simply after the regular expression to get the Flickr Image ID and don’t want to read all my waffle below (i like your style) then I'll save you the trouble.

.Net Regular Expression with grouping:


JavaScript Regular Expression


The photo page URL format

Flickr’s photo pages use the following URL format:[FLICKR USERNAME]/[FLICKR PHOTO ID]/

For those of you retrieving Flickr photos from Flickr using their API (i love FlickrNet for retrieving images using .Net – check it out) you’ll know that usually you want to know the Flickr photo ID (the second part of the URL) to do anything with the image using the API. So we need a regular expression that will extract the photo ID part of the above URL.

We could do this a number of other ways but i like RegExs for their power and simplicity.

How to validate a valid URL has been entered

As everyone developer has gathered the knowedge over time: Users can be stupid. Therefore if we have a user entering their photo URL’s we want to make suer that they have entered a valid URL before they do a postback to save them time.

Using the JavaScript RegEx i have provided above it is quite simple to just add a Regular Expression validator to your entry page to check the field for a valid URL. I have provided an example below.

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
    ErrorMessage="You must enter a valid Flickr URL" 

Retrieving the value in c#

So now that we know that the user has entered a valid Flickr photo URL using the above regular expression validator we want to extract just the image ID from the string for use. As i mentioned above i have used a regular expression grouping to give my photo ID an easy to reference name – so lets get it out.

Match match = Regex.Match(flickrURL, "photos/[^/]+/(?<imgID>[0-9]+)",
                          RegexOptions.IgnoreCase | 
if (match.Success)
   string FlickrPhotoID = match.Groups["imgID"].Value;

Too easy!