pythonformatterbbcode

BBCode parser to HTML


I use the BBCode Library to format some bbcode texts.

I write the next code :

import bbcode
import re

# Installing simple formatters.
parser = bbcode.Parser()
parser.add_simple_formatter('p', '<p>%(value)s</p>')

text = '[p]I am a text example[/p]'

# regex to extract text between [p] and [/p] tags
regex = r'\[p\](.*?)\[/p\]'

# extract text between [p] and [/p] tags
list_of_results = re.findall(regex, text)

html = parser.format(list_of_results[0])
print(html)

but the output is the following:

Output

I am a text example

Expected

<p>I am a text example</p>

I would like to know if is correct the way to call the simple formatter?


Solution

  • It's because you used group brackets in a regular expression

    One of the ways - just move the group brackets in your regex to cover all the tag, like this:

    regex = r'(\[p\].*?\[/p\])'
    

    In this way the output will be as expected:

    <p>I am a text example</p>
    

    But also, you don't need to use regex in this example, so following code will be just fine, giving the same result:

    import bbcode
    
    # Installing simple formatters.
    parser = bbcode.Parser()
    parser.add_simple_formatter('p', '<p>%(value)s</p>')
    
    text = '[p]I am a text example[/p]'
    
    html = parser.format(text)
    print(html)