在markdown中取消/评论html标签的流畅方式

时间:2013-12-11 01:05:41

标签: python html regex lambda

我正在尝试找到一种在html注释中包装html标签的好方法,而无需编写5个函数和50行代码。使用示例代码:

<section class="left span9">
### Test
</section>

我需要将其转换为:

<!--<section class="left span9">-->
### Test
<!--</section>-->

我有一个正则表达式来找到标签

re.findall('<.*?>', str)

但在过去的几年里,我并没有经常使用lambdas,所以现在我很难让它工作。

btw反过来这个过程的任何想法 - 取消标记?

2 个答案:

答案 0 :(得分:2)

您可以使用像这样的简单replace评论/取消注释

myString = '<section class="left span9">'
print myString.replace("<", "<!--<").replace(">", ">-->")
print myString.replace("<!--", "").replace("-->", "")

<强>输出:

<!--<section class="left span9">-->
<section class="left span9">

注意:这是有效的,因为有效的HTML文档只应在HTML标记中包含<>。如果它们应该按原样显示在输出中,则必须使用&gt;&lt;

正确地对其进行HTML转义

答案 1 :(得分:0)

好的,暂时我最终使用了两个函数和re.sub:

def comment(match):
    return '<!--'+match.group(0)+'-->'

def uncomment(html):
    return html.replace('<!--', '').replace('-->', '')

commented_html = re.sub('<.*?>', comment, html_string)

uncommented_html = uncomment(commented_html)