2013-01-02 38 views
0

我创建一个博客网站,在那里我将允许用户输入代码中[代码]代码的内容[/代码]更换多个[代码]块

会有多[编号]块这样的一篇博文。

我想用正则表达式来找到每个[代码]块,然后用

<pre>command 

此外,我想替换&lt;&gt;预标签内部<>

替换它现在我发现有用的代码这可以帮助我通过,但我与正则表达式混淆,有人可以帮助我。从使用RegexBuddy

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

..如果你找到了一些有用的代码..你为什么需要帮助吗?也许你想分享一个错误? –

+0

如果你可以讨论你感到困惑的部分,这将有所帮助。 – NotMe

+0

我很迷惑Regex.Match行。我想找到[代码] --- [/代码]块,并与此混淆。感谢任何帮助。谢谢 –

回答

2

..explanation:

\[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#..

+0

非常感谢您的帮助。你太棒了 :) –