2

I am pretty inexperienced when it comes to regular expressions and wondered if anyone can help me achieve the following.

I need a regular expression that will validate if a certain URL is a valid imgur image and return the ID of the image.

 Match imgurMatch = imgurRegex.Match(URL);
 if(imgurMatch.Success)
    id = imgurMatch.Groups[0].Value 

Here are some examples:

https://i.stack.imgur.com/1uGCs.jpg (ID = qtPdb)

https://i.stack.imgur.com/skRRh.jpg (ID = RcVIa)

(Could be of type .jpg, .png, .gif)

https://i.stack.imgur.com/3o0jW.jpg (ID = 3ZZuG)

I think a regular expression that can handle the above and return the correct ID would be good enough for me, since even if validation fails for some reason, I will be able to handle it in another way.

Please let me know if any more details is needed.

Thanks!

Tribe84

tribe84
  • 5,432
  • 5
  • 28
  • 30

1 Answers1

6
Regex imgurRegex=new Regex(@"http://(?:i\.imgur\.com/(?<id>.*?)\.(?:jpg|png|gif)|imgur\.com/(?:gallery/)?(?<id>.*))$");
Match imgurMatch = imgurRegex.Match(URL);
if(imgurMatch.Success)
   id = imgurMatch.Groups["id"].Value  
Bob Vale
  • 18,094
  • 1
  • 42
  • 49