我正在尝试在python中制作一个markdown解析器,不是因为它有用,而是因为它很有趣并且因为我正在尝试学习正则表达式。
#! /usr/bin/env python
#-*- coding: utf-8 -*-
import re
class Converter:
def markdown2html(self, string):
string = re.sub('\*{3}(.+)\*{3}', '<strong>\\1</strong>', string)
string = re.sub('\*{2}(.+)\*{2}', '<i>\\1</i>', string)
string = re.sub('^#{1}(.+)$', '<h1>\\1</h1>', string, flags=re.MULTILINE)
string = re.sub('^#{2}(.+)$', '<h2>\\1</h2>', string, flags=re.MULTILINE)
return string
markdown_sting = """
##h2 heading
#H1 heading
This should be a ***bold*** char
#anohter h1
anohter ***bold***
this is a **italic** string
"""
converter = Converter()
print converter.markdown2html(markdown_sting)
它打印
<h1>#h2 heading</h1>
<h1>H1 heading</h1>
This should be a <strong>bold</strong> char
<h1>anohter h1</h1>
anohter <strong>bold</strong>
this is a <i>italic</i> string
如您所见,它不解析 h2 标签。我哪里出错了?