我正在创建一个博客网站,我将允许用户在[代码]代码内容[/代码]
中输入代码在一篇博文中会有多个[Code]块。
我想使用Regex找到每个[Code]块,然后用
替换它<pre>command
另外,我想将pre tag中的<
和>
替换为&lt; &GT;
现在我发现有用的代码可以帮助我解决这个问题,但我对正则表达式感到困惑,有人可以帮我解决这个问题。
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();
}
答案 0 :(得分:2)
..来自RegexBuddy的解释:
\[pre=(?<lang>[a-z]+)\](?<code>.*?)\[/pre\]
Match the character “[” literally «\[»
Match the characters “pre=” literally «pre=»
Match the regular expression below and capture its match into backreference with name “lang” «(?<lang>[a-z]+)»
Match a single character in the range between “a” and “z” «[a-z]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “]” literally «\]»
Match the regular expression below and capture its match into backreference with name “code” «(?<code>.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “[” literally «\[»
Match the characters “/pre” literally «/pre»
Match the character “]” literally «\]»
要使其适用于[Code][/Code]
,您可以将其更改为:
\[code\](?<code>.*?)\[/code\]
..请记住,这只适用于单行块。此外,只有code
组...不再有lang
组..所以从C#中删除它..