Python + REGEX - Rich Text Formatter

291 views Asked by At

I am building a rich text formatter which does five things.

  1. multiline formatting
  2. bold text
  3. italic text
  4. >quote
  5. single line

I have been able to successfully pass through content to the formatter function which includes all examples packed into the one message. The problem I am facing is how to write a function that is still DRY and allows for any number of the formatting options shown above to be applied. I apologise if the solution may seem obvious I am very new to programming and I can't seem to think of a solution with out lots of repetition.

import re

class Publisher():


def rich_text_formatter(self, content):

    # Quote_format
    #find the desired string inside of the post content
    string = re.findall(r">([^;]*)\r\n", content)
    #if the desired string existed.
    if string:
        #concatenate html tags around the extracted string while turning list into a string for concatention.
        formatted_text = "<div class='quote-container'><div class='quote_bar'></div><span class='quote_format'>" + ', '.join(string) + " </span></div> "
        # insert formatted text back inside the post content replacing the unformatted string.
        final = re.sub(r">([^;]*)\r\n", formatted_text, content) 

    # Multi_line_format
        string = re.findall(r"\s```([^;]*)```\s", final)
        if string:
            formatted_text = " <br><pre class='multi_line_code_format'> " + ', '.join(string) + " </pre> "
            final = re.sub(r"\s```([^;]*)```\s", formatted_text, final) 

        # Bold_text_format
            string = re.findall(r"\s\*([^;]*)\*\s", final)
            if string:
                formatted_text = " <span class='bold_text_format'> " + ', '.join(string) + " </span> "
                final = re.sub(r"\s\*([^;]*)\*\s", formatted_text, final) 

            # Italic_text_format
                string = re.findall(r"\s_([^;]*)_\s", final)
                if string:
                    formatted_text = " <span class='italic_text_format'> " + ', '.join(string) + " </span> "
                    final = re.sub(r"\s_([^;]*)_\s", formatted_text, final) 

                # Single_line_format
                    string = re.findall(r"\s`([^;]*)`\s", final)
                    if string:
                        formatted_text = " <span class='single_line_format'> " + ', '.join(string) + " </span> "
                        final = re.sub(r"\s`([^;]*)`\s", formatted_text, final) 
                        return final

publisher = Publisher()
content = 'hey this is preformatted text ```multiline``` >this is a     quote\r\n' + '  `single line code` *bolded text* _italic_ '
print publisher.rich_text_formatter(content)
0

There are 0 answers