java查找和替换_java敏感字查找和替换
/*** @date 2020-12-09 009 19:36*/
public classSensitiveWordsSearch {/*** 關鍵字根節點*/
protectedWordsNode rootNode;/*** 所有關鍵字*/
protected ListsensitiveWordsList;/*** 關鍵字加載中*/
protected booleankeywordsLoading;privateSensitiveWordsSearch() {
}/*** 獲取實例
*
*@returnSensitiveWordsSearch*/
public staticSensitiveWordsSearch getInstance() {returnSensitiveWordsSearchInstance.INSTANCE;
}/*** 初始化關鍵字*/
private voidinitKeywords() {//初始化
rootNode = newWordsNode();for(SensitiveWords sensitiveWords : sensitiveWordsList) {
WordsNode node=rootNode;
String words=sensitiveWords.getWords();int length =words.length();for (int i = 0; i < length; i++) {
node=node.add(words.charAt(i));if (node.getLayer() == 0) {
node.setLayer(i+ 1);
}
}
node.setEnd(true);
node.setId(sensitiveWords.getId());
}
System.out.println(JSON.toJSONString(rootNode));
}/*** 更新關鍵字
*
*@paramsensitiveWordsList 關鍵字集合*/
public void updateKeywords(ListsensitiveWordsList) {if (!this.keywordsLoading) {this.keywordsLoading = true;this.sensitiveWordsList =sensitiveWordsList;this.initKeywords();this.keywordsLoading = false;
}
}/*** 獲取關鍵字
*
*@paramtext 檢索文本
*@parammaxMatch 最大匹配
*@return查找到的關鍵字*/
public List findWords(String text, booleanmaxMatch) {if (null ==rootNode) {throw new RuntimeException("SensitiveWordsSearch uninitialized.");
}
WordsNode top= null;
List list = new ArrayList<>();
WordsNode preNode= null;int length =text.length();int lastLength = length - 1;for (int i = 0; i < length; i++) {final char t =text.charAt(i);
WordsNode node;if (top == null) {
node=rootNode.getNode(t);
}else{if(top.hasKey(t)) {
node=top.getNode(t);
}else{if (maxMatch &&top.isEnd()) {
preNode=top;
}
node=rootNode.getNode(t);
}
}if(maxMatch) {//下一個節點
if (preNode != null) {//計算層級向前
list.add(new SearchNode(preNode.getWords(), i -preNode.getLayer(), i, preNode.getId()));
preNode= null;
}
}else{//當前節點
if (node != null &&node.isEnd()) {
list.add(new SearchNode(node.getWords(), i + 1 - node.getLayer(), i + 1, node.getId()));
}
}//最大匹配時修正最后一個文本無法匹配的問題
if (lastLength == i && maxMatch && node != null &&node.isEnd()) {//當前節點//最后匹配
list.add(new SearchNode(node.getWords(), i + 1 - node.getLayer(), i + 1, node.getId()));
}
top=node;
}returnlist;
}/*** 靜態內部類*/
private static classSensitiveWordsSearchInstance {/*** 實例對象*/
private static final SensitiveWordsSearch INSTANCE = newSensitiveWordsSearch();
}
}
總結
以上是生活随笔為你收集整理的java查找和替换_java敏感字查找和替换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java链式栈_Java栈之链式栈存储结
- 下一篇: java 设置光标_java光标位置怎么