import re def parse(markdown): lines = markdown.split('\n') result, in_list, finish_list = '', False, False for line in lines: # Heading formatting if re.match('###### (.*)', line) is not None: line = '
' + line[7:] + '
' elif re.match('## (.*)', line) is not None: line = '

' + line[3:] + '

' elif re.match('# (.*)', line) is not None: line = '

' + line[2:] + '

' # List detection is_list = re.match(r'\* (.*)', line) or False line = is_list.group(1) if is_list else line # Bold strongmatch = re.match('(.*)__(.*)__(.*)', line) if strongmatch: line = strongmatch.group(1) + '' + \ strongmatch.group(2) + '' + strongmatch.group(3) # Italics italicmatch = re.match('(.*)_(.*)_(.*)', line) if italicmatch: line = italicmatch.group(1) + '' + italicmatch.group(2) + \ '' + italicmatch.group(3) # If a list has been detected if is_list: if not in_list: line = '' + line is_list = False finish_list = False # Finish this line and add it to the result. result += line # If we have somehow not ended a list yet, complete it now. if in_list: result += '' return result