0

I'm looking for a way to linkify a string that contains the following...

Lorem ipsum, Lorem ipsom Instagram: @instausername Lorem ipsum

the code need to make this "Instagram: @instausername" into this "<a href='https://www.instagram.com/@instausername'> Instagram: @instausername<a/>". So the final string should look like this..

Lorem ipsum, Lorem ipsom <a href='https://www.instagram.com/@instausername'> Instagram: @instausername<a/> Lorem ipsum

I'm not that familiar with regex but I suppose it can be solved using regex, can anyone please help?

Pedro Lobito
  • 75,541
  • 25
  • 200
  • 222
MTplus
  • 1,113
  • 2
  • 19
  • 35

1 Answers1

1

An Instagram username is limited to 30 characters and must contain only letters, numbers, periods, and underscores. You can’t include symbols or other punctuation marks as a part of your username.

Based on this, you can use:

    string subjectString = "Lorem ipsum, Lorem ipsom Instagram: @instausername Lorem ipsum";
    string resultString = null;
    try {
        resultString = Regex.Replace(subjectString, "Instagram: (@[^ ]+)", "<a href='https://www.instagram.com/$1'> Instagram: $1<a/>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        Console.WriteLine(resultString);
    } catch (ArgumentException ex) {
        // Syntax error in the regular expression
    }

Lorem ipsum, Lorem ipsom <a href='https://www.instagram.com/@instausername'> Instagram: @instausername<a/> Lorem ipsum

Demo

Pedro Lobito
  • 75,541
  • 25
  • 200
  • 222
  • 1
    Thanks Pedro, worked fine. I just added a replace of the @ charachter in the link for the username. – MTplus Jan 27 '20 at 15:29