0

我正在创建一个博客站点,我将允许用户在 [代码] 代码内容 [/代码] 中输入代码

在一篇博文中会有多个像这样的 [代码] 块。

我想使用 Regex 找到每个 [Code] 块,然后将其替换为

<pre>command

&lt;我也想将&gt;pre 标签替换为 < >

现在我找到了有用的代码,可以帮助我解决这个问题,但我对正则表达式感到困惑,有人可以帮我解决这个问题。

    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();
}
4

1 回答 1

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# 中删除它..

于 2013-01-02T02:28:11.760 回答