Skip to main content
 首页 » 编程设计

python之制作 Markdown 解析器时的正则表达式问题

2025年05月04日24jiqing9006

我正在尝试用 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 标签。我哪里错了?

请您参考如下方法:

通过确保标题文本的第一个字符不是井号,您可以确保只匹配所需数量的井号。这可以通过使用 [^#] 来完成,如下所示:

string = re.sub('^#{1}([^#].*)$', '<h1>\\1</h1>', string, flags=re.MULTILINE) 
string = re.sub('^#{2}([^#].*)$', '<h2>\\1</h2>', string, flags=re.MULTILINE) 

这样规则的顺序就无关紧要了,使规则更加健壮。