替换多个[Code]块
本文关键字:Code 替换 | 更新日期: 2023-09-27 17:50:26
我正在创建一个博客网站,在那里我将允许用户在[code]内输入代码代码内容[/code]
在一篇博文中会有多个这样的[Code]块。
我想用Regex找到每个[Code]块,然后用
替换它<pre>command
我还想将前标签中的<
和>
替换为<>
现在我找到了有用的代码,可以帮助我通过,但我对Regex感到困惑,有人可以帮助我这个。
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();
}
…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#中删除