package com.smtaiserver.smtaiserver.javaai.ast; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.smtservlet.util.SMTStatic; public class ASTQuestionReplace { public Pattern _patQuestion; public Pattern _patReplace; public Map> _mapGroupType2Question2Replace; private static Logger _logger = LogManager.getLogger(ASTQuestionReplace.class); public ASTQuestionReplace(String sPatQuestion, String sPatReplace, Map> mapGroupType2Question2Replace) { _patQuestion = Pattern.compile(sPatQuestion); _patReplace = Pattern.compile(sPatReplace); _mapGroupType2Question2Replace = mapGroupType2Question2Replace; } public String replaceQuestion(String groupType, String question) { if(SMTStatic.isNullOrEmpty(question)) return ""; String curPatText = ""; try { Map mapQuestion2Replace = _mapGroupType2Question2Replace.get(groupType); if(mapQuestion2Replace == null) return question; Set setExists = new HashSet<>(); // 记录已经被替换后的文字 curPatText = _patReplace.pattern(); Matcher matcher = _patReplace.matcher(question); while(matcher.find()) { setExists.add(matcher.group()); } // 替换文字 String result = SMTStatic.replaceRegexText(question, _patQuestion, match -> { // 如果替换的文字没在字典表里则忽略 String replace = mapQuestion2Replace.get(match); if(SMTStatic.isNullOrEmpty(replace)) return match; // 如果被替换的文字已经存在再问题中则忽略 if(setExists.contains(replace)) return match; return replace; }); return result; } catch(Exception ex) { _logger.fatal("replaceQuestion exception : [" + curPatText + "]=>[" + question + "]", ex); return question; } } }