I am creating a blog site, where i will be allowing user to enter code inside [Code] Code Content [/Code]
There will be multiple [Code] blocks like this in one blog post.
I want to find each [Code] block using Regex and then replace it with
<pre>command
Also i want to replace < and > inside pre tag to < >
Now i found useful code which can help me through that but i am confused with Regex, can someone help me with this.
static string ProcessCodeBlocks(string value)
{
StringBuilder result = new StringBuilder();
Match m = Regex.Match(value, @"\[pre=(?<lang>[a-z]+)\](?<code>.*?)\[/pre\]");
int index = 0;
while( m.Success )
{
if( m.Index > index )
result.Append(value, index, m.Index - index);
result.AppendFormat("<pre class=\"{0}\">", m.Groups["lang"].Value);
result.Append(ReplaceBreaks(m.Groups["code"].Value));
result.Append("</pre>");
index = m.Index + m.Length;
m = m.NextMatch();
}
if( index < value.Length )
result.Append(value, index, value.Length - index);
return result.ToString();
}
..explanation from RegexBuddy:
To make it work for
[Code][/Code], you would change it to this:..keeping in mind this will only work for single-line blocks. Also, there is only a
codegroup.. there is nolanggroup anymore.. so remove that from the C#..