Python: markdown, iteration 2

This commit is contained in:
Dmitry Kokorin 2021-06-11 18:50:40 +03:00
parent a0535502eb
commit bae42c9a49

View file

@ -2,34 +2,29 @@ import re
def parse(markdown): def parse(markdown):
res = '' result = ''
in_list = False
for line in markdown.splitlines(): for line in markdown.splitlines():
match = re.match(r'^(#{1,6}) (.*)', line)
if match:
level = len(match.group(1))
res += f'<h{level}>{match.group(2)}</h{level}>'
continue
line = re.sub(r'__(.*)__', r'<strong>\1</strong>', line) line = re.sub(r'__(.*)__', r'<strong>\1</strong>', line)
line = re.sub(r'_(.*)_', r'<em>\1</em>', line) line = re.sub(r'_(.*)_', r'<em>\1</em>', line)
match = re.match(r'\* (.*)', line) match = re.match(r'^(#{1,6}) (.*)', line)
if match: if match:
if not in_list: level = len(match.group(1))
in_list = True result += f'<h{level}>{match.group(2)}</h{level}>'
res += '<ul>'
res += '<li>' + match.group(1) + '</li>'
continue continue
if in_list: match = re.match(r'\* (.*)', line)
in_list = False if match:
res += '</ul>'
res += '<p>' + line + '</p>' if result.endswith('</ul>'):
result = result[:-5]
else:
result += '<ul>'
if in_list: result += '<li>' + match.group(1) + '</li></ul>'
res += '</ul>' continue
return res result += '<p>' + line + '</p>'
return result