0

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.

1
  • Just posted a working example Commented Sep 24, 2012 at 21:12

1 Answer 1

2

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

good work man.. I was going for this baby but yours is simple and charming (!)((?:[a-z][a-z]+))(:)(\d+)(:)((?:[a-z][a-z]+))(.)((?:[a-z][a-z]+))(!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.