0

I'm implementing a library that will convert BBCode-like syntax to a corresponding html element. I can easily do it on simple element by using String.Replace function. 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>");

But with a complex element like [code class="c-sharp"][/code]. I don't know how to replace [code][/code] with <pre></pre> but still preserve the class="c-sharp" attribute. Is there any solution for this case without using regular expression? Because I want to preserve the readability of my code.

Doan Cuong
  • 2,594
  • 4
  • 22
  • 39

1 Answers1

2

Here is code:

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

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

Hint: You can use the first and second replaces as default because it's common between your scenarios.

Example using LinqPad

Emad Mokhtar
  • 3,237
  • 5
  • 31
  • 49