我有以下字符串:
<html>
<head><meta>...</meta><head>
<body>
<div id="foo">
Text I want to search & replace occurrences
of keywords such as Foo or foo while ignoring case
</div>
</body>
</html>
我想要的最终结果是:
<html>
<head><meta>...</meta><head>
<body>
<div id="foo">
Text I want to search & replace occurrences
of keywords such as <b>Foo</b> or <b>foo</b> while ignoring case
</div>
</body>
</html>
我非常想搜索并替换 foo
与 <b>foo</b>
或<b>Foo</b>
。重要的是保留要替换的字符串的大小写,但将其与关键字 foo
匹配。同时忽略匹配的情况。
另一个重要的事情是替换会忽略所有 html 标签及其内容。请注意 <div id="foo">
保持原样。
我起草了这个,但尚未测试
text = text.replace("(?i)"+keyword+"(?!([^<]+)?>)", "<b>"+keyword+"</b>");
上面的问题是它不记得要替换的单词的大小写,只是输入关键字。
最佳答案
text.replaceAll("(?i)(" + keyword + ")(?!([^<]+)?>)", "<b>$1</b>")
关于java - 使用Java替换HTML页面字符串中的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4765058/