我有这样的东西:
<p id="tire">I need new tires for my car</p>
我正在尝试编写一些内容来突出显示我指定的单词,但不突出显示被视为标签的内容。例如,如果我想突出显示“轮胎”,理论上我会看到:
<p id="tire">I need new <strong>tire</strong>s for my car</p>
但不幸的是,我看到:
<p id="<strong>tire</strong>">I need new <strong>tire</strong>s for my car</p>
我只使用一个简单的replaceAll(oldWord, newFormat)。有图书馆可以提供帮助吗?我正在使用 jsoup 来获取我要搜索的 HTML。
最佳答案
您可以使用选择方法getElementsContainingOwnText(String searchText)
来选择包含您要查找的单词的元素。在本例中为“轮胎”。
作为其工作原理的示例:
虚拟 HTML
<html>
<head></head>
<body>
<p id="tire">I need new tires for my car</p>
</body>
</html>
我们的 Jsoup 代码:
Elements e = doc.getElementsContainingOwnText("tire");
for (Element el : e) {
el.text(el.ownText().replace("tire", "<strong>tire</strong>"));
}
最终的文档打印输出:
<html>
<head></head>
<body>
<p id="tire">I need new <strong>tire</strong>s for my car</p>
</body>
</html>
关于java - 查找段落中的非 HTML 标记词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19304241/