【问题标题】:c# Regex replace <br /> or [br /] to "\n" between [pre=html]code[br /]code[/pre]c# Regex 将 [pre=html]code[br /]code[/pre] 之间的 <br /> 或 [br /] 替换为 "\n"
【发布时间】:2011-07-17 00:18:15
【问题描述】:

我有将 BBCode 替换为 html 的代码,当我想替换 &lt;br /&gt;[br /] 中的标签 [pre=html] code [/pre] 时出现问题。

Regex exp; string str;

 str = "more text [pre=html] code code code code [br /] code code code [br /] code code [/pre] more text";

 str = str.Replace("[br /]","<br />");

 exp = new Regex(@"\[b\](.+?)\[/b\]");
 exp.Replace str = (str,"<strong>$1</strong>");
 ......
 exp = new Regex (@ "\[pre\=([a-z\]]+)\]([\d\D\n^]+?)\[/pre\]");
 str = exp.Replace(str, "<pre class=\"$1\">" + "$2" + "</pre>");

正如您将&lt;br /&gt;[br /] 更改为[pre=html] code [/pre]&lt;pre class=html&gt; code &lt;/pre&gt; 内的“\n”

【问题讨论】:

  • 您遇到了什么问题?多一点解释将有助于我们为您提供帮助。

标签: c# asp.net-mvc regex replace


【解决方案1】:

一般来说,几乎不可能表达这样的约束条件,即某些东西必须在单个正则表达式中的一对匹配的其他东西之间才能匹配。

将其拆分为多个操作更容易,您首先找到[pre] 块,然后分别处理它们的内容。它还使您的代码更易于编写、理解和调试。

以下是如何完成此操作的示例:

static string ReplaceBreaks(string value)
{
    return Regex.Replace(value, @"(<br */>)|(\[br */\])", "\n");
}

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

您必须根据需要对其进行修改以执行进一步的处理,但我认为这会让您开始。

【讨论】:

  • 哇,我看到解决方案不是那么简单。好朋友,感谢您的帮助,您的建议相当详尽,当然,我要根据我的问题进行修改!谢谢和问候。
  • 猜得有点晚了,但这对于
    检测来说可能是一个更灵活的正则表达式(因为空格可以出现在任何地方,并且您也希望支持
    元素:()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 2011-05-21
  • 2012-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多