Search code examples
c#regeximgur

imgur extract codes from links in C# Regex


I'm trying to convert a imgur link to an embedded code.

I've found this Regex that works to extract the imgur code in JavaScript. I need your help in a code that extracts one or more matching imgur links from a string in c#.

Here is the JavaScript equivalent:

https://regex101.com/r/qI4lY7/3

The regex return matches the entire string starting from the http. So if I have the following string.

string a = "bla b la alb http://imgur.com/a/BmFoY#5i4b8Zz dsfs df";

The regex used:

  Regex regex = new Regex(@"(https?:\/\/imgur\.com\/a\/(.*?)(?:[#\/].*|$))");

The match.value for the following code:

 Match match = regex.Match(a);

Returns:

http://imgur.com/a/BmFoY#5i4b8Zz dsfs df

Which is not what I want to achieve. I need the matching code from the link, which is BmFoY in case of the example above.


Solution

  • Consider to grab everything from http://imgur.com to first space

    var regex = new Regex(@"https?://imgur\.com/a/([^\s]+)");
    

    Group will contain

    "BmFoY#5i4b8Zz"