简体   繁体   中英

How can I extract a string from within a regex?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM