用条件替换字符串

时间:2013-12-31 07:37:52

标签: c# str-replace

我正在实现一个库,它将BBCode - 类似语法转换为相应的html元素。我可以使用String.Replace函数在简单元素上轻松完成。 E.x:

string text = "this is [b]some text that need to parse[/b] and more text to make it more complicated [i]and then more text that need to parse[/i], how fun";
text = text.Replace("[b]", "<b>");
text = text.Replace("[/b]", "</b>");
text = text.Replace("[i]", "<i>");
text = text.Replace("[/i]", "</i>");

但是有一个复杂的元素,如[code class="c-sharp"][/code]。我不知道如何将[code][/code]替换为<pre></pre>,但仍保留class="c-sharp"属性。在不使用regular expression的情况下,是否有针对此案例的解决方案?因为我想保留代码的可读性。

1 个答案:

答案 0 :(得分:2)

这是代码:

string s = "[code class='c-sharp'][/code]";
StringBuilder pre = new StringBuilder(s);

pre.Replace("[","<");
pre.Replace("]",">");
pre.Replace("code","pre");

提示:您可以使用第一次和第二次替换作为默认值,因为它在您的方案之间很常见。

Example using LinqPad