0

I am needing to pattern match some text and replace it with some HTML.

Currently I am using the following regex to find [v AnyTextHere] in my C# MVC 3 project.

\\[[v] (.*?)\\]

The problem I am having, is that once I locate the above text, I then want to replace the start and end but keep the text in the middle. So for example:

[v AnyTextHere]

becomes

<p>AnyTextHere</p>

I have thought about putting all of the matches in to an array trimming the start and end and then replacing them back with the HTML around them. However I'm sure there is a much better way if I were to be a master of regex, which I am not!

I should also add the the AnyTextHere section will have no spaces but is out of my control as to what the value may be. There may also be more than one match per page, however each match can only appear once.

I hope that makes some sense.

Many thanks in advance.

1 Answer 1

4

Try this:

string input = "[v AnyTextHere]";
string htmlOutput = Regex.Replace(input, "\\[v (.*?)\\]", "<p>$1</p>");

How this works: the $1 refers to the value that's inside the first parentheses, .*? in this case. It's also not necessary to put the v in a character class, because there's just one character allowed, so you can replace [v] with v

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your fast response. This was exactly what I needed.

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.