日期:2014-05-17 浏览次数:20918 次
public static void main(String[] args) {
String str1 = "<p>这是一篇文章,用来介绍金庸先生的一本<B>名著天龙八部</B>。天龙八部是金庸先生的一部著名唱片武侠小说……,天龙八部人物关系复杂……。</p>";
List<String> lists = new ArrayList<String>();
Pattern p = Pattern.compile("<B>.*?</B>");
Matcher m = p.matcher(str1);
while(m.find()){
String tmp = m.group();
lists.add(tmp);
str1 = str1.replaceFirst("<B>.*?</B>", "---");
}
str1 = str1.replaceAll("天龙八部", "<B>天龙八部</B>");
for(String ele:lists){
str1 = str1.replaceFirst("---", ele);
}
System.out.println(str1);
}
------解决方案--------------------
for example
String s = "<p>这是一篇文章,用来介绍金庸先生的一本<B>名著天龙八部</B>。天龙八部是金庸先生的一部著名唱片武侠小说……,天龙八部人物关系复杂……。</p>";
String keyword = "天龙八部";
boolean ok = false;
Pattern p = Pattern.compile("(?i)<b>(.*?)</b>");
Matcher m = p.matcher(s);
List<int[]> list = new ArrayList<int[]>();
while (m.find()) {
if (m.group(0).contains(keyword)) {
list.add(new int[]{m.start(), m.end()});
}
if (keyword.equals(m.group(1))) {
ok = true;
break;
}
}
if (! ok) {
int index = s.indexOf(keyword);
while (index >= 0) {
ok = true;
for (int[] idx : list) {
if (index > idx[0] && index < idx[1]) {
ok = false;
}
}
if (ok) {
s = s.substring(0, index-1) + "<B>" + keyword + "</B>" + s.substring(index+keyword.length());
break;
}
index = s.indexOf(keyword, index+1);
}
}
System.out.println(s);