java關鍵字加鏈接 正則
代碼如下:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
import java.util.HashMap;
import java.util.regex.Pattern;
/**
*
* @author dragon
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String source ="從前有個山,山裏有個廟,廟裏有個老和尚。老和尚在給小和尚講這樣一個故事:從前有個山,山裏有個廟.....";
String keyword ="和尚";
String link ="http://www.yourlink.com";
System.out.println(Main.addKeywordLink(source,keyword,link));
}
public static String addKeywordLink(String source,String keyword,String link){
return source.replaceAll("(?!((<.*?)|(<a.*?)))("+keyword+")(?!(([^<>]*?)>)|([^>]*?</a>))", "<a href=/""+link+"/">"+keyword+"</a>");
}
}