我想编写一个突出显示某些文本的函数。 它以 HTML 字符串作为输入并返回带有附加 html 标记的 HTML 字符串。
例子: 输入字符串(需要高亮“文本”一词):
<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 ???
还有其他想法吗?
最佳答案
关于Python。替换 html 标签之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4069453/