蟒蛇。替换html标记之间的文本

时间:2010-11-01 13:50:40

标签: python html regex tags replace

我想写一个突出显示某些文字的功能。 它将HTML字符串作为输入,并返回带有其他html标记的HTML字符串。

实施例: 输入字符串(需要突出显示“text”一词):

<div>
<a href="..." title="text to highlight">Some text to highlight</a>
<a href="..." title="text to highlight">Some other text to highlight</a>
</div>

输出字符串:

<div>
<a href="..." title="text to highlight">Some <b class="highlight">text</b> to highlight</a>
<a href="..." title="text to highlight">Some other <b class="highlight">text</b> to highlight</a>
</div>

我找到了一个只在html标签之间匹配文字的正则表达式,但我无法弄清楚如何用其他标签包围它的某些部分

highlight_str = u'text'
p = re.compile(r"[^<>]+(?=[<])")
    iterator = p.finditer(search_str)
    for match in iterator:
        # code for replacement here ???

还有其他想法吗?

1 个答案:

答案 0 :(得分:4)

看看Beautiful Soup

相关问题