最近公司需要对名称进行关键词替换,于是简单写了个关键词替换工具类
还能添加许多功能和进行优化,欢迎大家使用
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
import java.util.Set;
public class keywordUtil {
public static JSONObject keywordJson = new JSONObject();
private static final String END = "end";
private static final String SUBSTITUTE = "*";
public static void readDatasource(Set keywordSet) {
for (String keyword: keywordSet) {
initKeywordJson(keyword, 0, keywordJson);
}
}
public static String replace(String text) {
for (int i = 0; i < text.length(); i++) {
StringBuilder sb = new StringBuilder();
search(text, i, keywordJson, sb);
if (sb.length() == 0) {
continue;
}
text = text.replaceAll(sb.toString(), generateSubstitute(sb.length()));
}
return text;
}
private static void initKeywordJson(String keyword, int index, JSONObject sourceJson) {
if (keyword.length() == index) {
sourceJson.put(END, true);
return;
}
String str = String.valueOf(keyword.charAt(index));
JSONObject tmpJson = sourceJson.getJSONObject(str);
if (tmpJson == null) {
sourceJson.put(str, new JSONObject());
}
initKeywordJson(keyword, ++index, sourceJson.getJSONObject(str));
}
private static boolean search(String text, int index, JSONObject sourceJson, StringBuilder targetBuilder) {
if (text.length() == index) {
return false;
}
String str = String.valueOf(text.charAt(index));
if (str.equals(SUBSTITUTE)) {
return false;
}
JSONObject tmpJson = sourceJson.getJSONObject(str);
if (CollectionUtils.isEmpty(tmpJson)) {
return false;
}
if (tmpJson.containsKey(END) && tmpJson.getBoolean(END)) {
targetBuilder.append(str);
return true;
}
boolean result = search(text, ++index, sourceJson.getJSONObject(str), targetBuilder);
if (result) {
targetBuilder.insert(0, str);
}
return result;
}
private static String generateSubstitute(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(SUBSTITUTE);
}
return sb.toString();
}
}
依赖
org.apache.commons commons-lang3 3.12.0 com.alibaba fastjson 1.2.49



