Insane Programming Java ramblings and finds on the net

8Jun/102

Code Kata: BBCode

Here's a nice code kata: convert BBCode to HTML. So [b]test[/b] becomes <strong>test</strong>, etc... Provide tags for all the basic BBCode tags: i, u, b, img, url, li, ol, ul and newlines.

For you cheaters, here's my implementation, using regex:

import org.springframework.web.util.HtmlUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BBCodeConverter {

    public static String convertString(String bbCodeString)
    {
        bbCodeString = HtmlUtils.htmlEscape(bbCodeString);
        for(BBCodeTag tag : BBCodeTag.values())
        {
            bbCodeString = tag.convert(bbCodeString);
        }
        return bbCodeString;
    }

    private enum BBCodeTag
    {
        B("\\[b\\](.*?)\\[/b\\]", "<strong>$1</strong>"),
        I("\\[i\\](.*?)\\[/i\\]", "<em>$1</em>"),
        U("\\[u\\](.*?)\\[/u\\]", "<span style=\"text-decoration:underline\">$1</span>"),
        NEWLINE("\n", "<br/>"),
        IMG("\\[img\\](.*?)\\[/img\\]", "<img src=\"$1\"></img>"),
        URL("\\[url=(.*?)\\](.*?)\\[/url\\]", "<a href=\"$1\">$2</a>"),
        UL("\\[ul\\](.*?)\\[/ul\\]","<ul>$1</ul>"),
        OL("\\[ol\\](.*?)\\[/ol\\]","<ol>$1</ol>"),
        LI("\\[li\\](.*?)\\[/li\\]","<li>$1</li>"),
        SIZE("\\[size=(.*?)\\](.*?)\\[/size\\]","<span style=\"font-size:$1%\">$2</span>"),
        COLOR("\\[color=(.*?)\\](.*?)\\[/color\\]","<span style=\"color:$1\">$2</span>")
        ;
        private String tagPattern;
        private String htmlConversion;

        private BBCodeTag(String tagPattern, String htmlConversion) {
            this.htmlConversion = htmlConversion;
            this.tagPattern = tagPattern;
        }

        public String convert(String bbCodeTag)
        {
            Pattern pattern = Pattern.compile(tagPattern);
            Matcher matcher = pattern.matcher(bbCodeTag);
            String replaced = matcher.replaceAll(htmlConversion);
            return replaced;
        }
    }
}
Comments (2) Trackbacks (0)
  1. Nice, haven’t tried it yet, but does it support nested BB code tags?

  2. It should, it does at least for the lists.


Leave a comment


Spam protection by WP Captcha-Free

No trackbacks yet.