我想編寫一個突出顯示某些文本的函數。 它需要一個HTML字符串作爲輸入並返回帶有附加html標籤的HTML字符串。Python。替換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 ???
有沒有其他想法可以做到這一點?
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – user470379 2010-11-01 13:52:16
嚴重的是,在HTML上使用正則表達式的程序員的遊行是無止境的。 – hughdbrown 2010-11-01 14:31:02
該正則表達式不適用於任何其他操作,而不適用於操縱演示。 – tchrist 2010-11-01 14:31:59