すでにhtmlタグを用いて記述された文章msg
を、与えられたキーワードkeyword
でくくるプログラム。
public static void main(String args[]){ String keyword = "o"; String msg = " I am a google user.<a href=\"http://www.google.co.jp\" target=\"_blank\">http://www.google.co.jp</a>If you click this link, you go to google."; Boolean inTag = false; String regex = "((" + keyword + ")+)"; if (msg == null || msg.length() <= 0) { System.out.println(msg); } int len = msg.length(); int st = 0; char[] val = msg.toCharArray(); StringBuffer result = new StringBuffer(); StringBuffer temp = new StringBuffer(); while ((st < len)) { if(inTag == false){ temp.append(val[st]); if(val[st]=='<'){ inTag = true; String highLighted = temp.toString().replaceAll(regex,"<span>$1</span>"); result.append(highLighted); temp.delete(0, temp.length()); } }else if(inTag == true){ result.append(val[st]); if(val[st] == '>'){ inTag = false; } } st++; } if(st == len && inTag == false){ result.append(temp.toString().replaceAll(regex,"<span>$1</span>")); } System.out.println(result.toString()); } }
結果は
I am a g<span>oo</span>gle user. <a href="http://www.google.co.jp" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://www.google.co.jp']);" target="_blank"> http://www.g<span>oo</span>gle.c<span>o</span>.jp </a> If y<span>o</span>u click this link, y<span>o</span>u g<span>o</span> t<span>o</span> g<span>oo</span>gle.
のようになる。