JCisar
JCisar

Reputation: 2674

Regex.Replace to create hyperlink C#

I am trying to use Regex.Replace to create a hyperlink. I want to make it so the user can hit a button that I have created and create a product link. This way if the url changes for some reason it I wont have to change the logic in the data entry side. The user will be submitting a body of text and I will have something formatted like this:

"[!product:123456:Click Me!]" 

Where p stands for product. Click Me is the text displayed on the link. 123456 is the identifier. The link should look like this:

<a href="www.mywebsite.com/product/123456">Click Me</a>

So far I have this:

var output = Regex.Replace(model.Body, @"\[!([^!]*)\!]", "<a href='http://www.mywebsite.com/$1'> link </a>");

Which returns:

 http://www.mywebsite.com/p:165411:Click Me

Is there any way I can do a Regex that will allow me to parse between [! and !] to seperate out the data that is seperated by ":"?

Here is what I am thinking:

var output = Regex.Replace(model.Body, SOME REGEX HERE, "<a href='http://www.mywebsite.com/$1/$2'> $3 </a>");

Hopefully this is enough information on what I am trying to do. Any help would be greatly appreciated.

Upvotes: 0

Views: 317

Answers (1)

CaffGeek
CaffGeek

Reputation: 22064

How about this regex?

\[!(.*):(.*):(.*)!\]

In c# that is

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "[!product:123456:Click Me!]";
            var regex = new Regex("\\[!(.*):(.*):(.*)!\\]", RegexOptions.IgnoreCase);

            var result = regex.Replace(text, "<a href='http://www.mywebsite.com/$1/$2'> $3 </a>");
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

Upvotes: 2

Related Questions