2

Can anyone help me write a regex have below result to replace bbcode with html tag, for here i want to replace [b][/b] with <strong></strong>

So this:

 "fsdfs [b]abc[/b] dddfs [b]abc[/b] fdsfdsfs [b]abcfsdfs" 

Becomes:

 "fsdfs <strong>abc</strong> dddfs <strong>abc</strong> fdsfdsfs [b]abcfsdfs"

Would the following Regex help to solve this problem?

 string result = Regex.Replace(s, @"\[b\](.*?)\[\/b\]", @"\<stront\>(.*?)\<\/strong\>");
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
leo
  • 43
  • 6
  • `` should probably be `` what ever you try to do. – gdoron Apr 10 '13 at 23:19
  • I understood it, the question was essentially: how can I convert `"fsdfs [b]abc[/b] dddfs [b]abc[/b] fdsfdsfs [b]abcfsdfs"` to `"fsdfs abc dddfs abc fdsfdsfs [b]abcfsdfs"` with regex. Putting both the input and output on the same line was an unfortunate choice. – Andrew Clark Apr 10 '13 at 23:21
  • I'm guessing that you only want to replace [B] with [STRONG] where the [B] has a closing [/B] in the original string. This is not a good thing to do in Regex, because regex is not good for parsing HTML. Why? Read this: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1758162 – Russ Clarke Apr 10 '13 at 23:21
  • Why are you escaping the angle brackets in the replacement? – Kenneth K. Apr 10 '13 at 23:24

1 Answers1

5

The following should work:

string s = "fsdfs [b]abc[/b] dddfs [b]abc[/b] fdsfdsfs [b]abcfsdfs";
string result = Regex.Replace(s, @"\[b\](.*?)\[/b\]", @"<strong>$1</strong>");

Example: http://ideone.com/xwP1EL

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 1
    As a thought experiment, this works very well. In practice though, it's not a good way to manage Html at all; It can't hurt to consider using something like the Html Agility pack instead. http://stackoverflow.com/questions/6540154/html-agility-pack-c-how-to-create-replace-tags – Russ Clarke Apr 10 '13 at 23:38