package cc.unmi.utils;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import jregex.Pattern;
import jregex.Replacer;
public class StringUtils {
public static String replaceStringByJS(String src, String jsRegex, String replacement) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script =
"function rep(target, regex, replacement){\n"
+ " var patt = new RegExp(regex,'g');\n"
+ " return target.replace(patt, replacement);\n"
+ "}";
try {
engine.eval(script);
Invocable inv = (Invocable) engine;
String result = (String) inv.invokeFunction("rep", src, jsRegex,
replacement);
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String replaceStringByJRegex(String src, String regex, String replacement) {
Pattern pattern = new Pattern(regex);
Replacer replacer = pattern.replacer(replacement);
String result = replacer.replace(src);
return result;
}
public static void main(String[] args) {
String link="<link url=\"http://unmi.cc\" >\"Home\"</link>"
+"<link url=\"http://yanbin.blog/tag/java\" >\"Java\"</link>";
String jsString = StringUtils.replaceStringByJS(link,
"<link\\s+url=\\\"(.+?)\\\".[^/]*?>\\\"(.+?)\\\"</link>", "<a href=\"$1\">$2</a>");
System.out.println(jsString);
String jregexString = StringUtils.replaceStringByJRegex(link,
"<link\\s+url=\\\"(.+?)\\\".[^/]*?>\\\"(.+?)\\\"</link>", "<a href=\"$1\">$2</a>");
System.out.println(jregexString);
}
/*
* 程序输出
* <a href="http://unmi.cc">Home</a><a href="http://yanbin.blog/tag/java">Java</a>
* <a href="http://unmi.cc">Home</a><a href="http://yanbin.blog/tag/java">Java</a>
*/
}