Python implementation of BBCode?

Ian Bicking ianb at colorstudy.com
Tue Dec 3 17:42:02 EST 2002


On Tue, 2002-12-03 at 14:31, Terry Hancock wrote:
> I could, of course, write one, but I'm not sure about the right approach -- I 
> don't think the XML tools can be used on it, so I suppose I'd need to use the 
> re module. There's also stripogram, which might be adapted, I suppose.   I'd 
> also have to find a definitive spec to write to.

It sounds fairly simple, from what you describe.  E.g.:

boldRE = re.compile(r'\[b\](.*?)\[/b\]', re.MULTILINE)
urlRE = re.compile(r'\[url(?:=([^]]*))?\](.*?)\[/url\]', re.MULTILINE)
newlineRE = re.compile(r'\r?\n(?:\r\n)+')
def convertBBCode(text):
    text = boldRE.sub('<b>\1</b>', text)
    text = urlRE.sub(urlSubber, text)
    text = newlineRE.sub('<p>\n', text)
    return text

def urlSubber(match):
    # if no url=... given, default to text inside [url][/url]
    url = match.group(1) or match.group(2)
    return '<a href="%s">%s</a>' % (url, match.group(2))


Obviously incomplete, and probably has typos, but it should be easy
enough to finish up.  The regular expressions wouldn't look so bad if
you didn't have to put a \ before every [.

If you want a different markup, restructured text is pretty nice.  It's
more Wiki-style, and a bit more weighty, but pretty decent.  I think
it's better than most ad hoc Wiki markup.  But it's not as appropriate
for casual writing -- it doesn't mimic normal conventions as much as
most Wiki markups, and it doesn't leverage HTML knowledge, like HTML
input or the BBCode you describe.

If you want to be fancy, it only takes a small amount of code to get
IE5.5+ to allow more WYSIWYG-like editing.


-- 
Ian Bicking <ianb at colorstudy.com>




More information about the Python-list mailing list