0

私はブログサイトを作成しています。そこでは、ユーザーが[コード]コードコンテンツ[/コード]内にコードを入力できるようにします。

1つのブログ投稿にこのような複数の[Code]ブロックがあります。

正規表現を使用して各[Code]ブロックを検索し、それを次のように置き換えたい

<pre>command

&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();
}
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 に答える