【发布时间】:2011-06-13 11:56:44
【问题描述】:
我有以下字符串:
<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>");
上面的问题是它不记得要替换的单词的大小写,而只是放入关键字。
【问题讨论】: