import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * Title:脏词过滤 * Author:zhouzhl */ public class Test { public static void main(String[] args) throws Exception { String filterText = "非法黄色漫天飞!"; // System.out.println(Test.getFilterText(filterText)); } /* * @param 要过滤的文章内容 @return 返回过滤后的内如 */ public static String getFilterText(String filterText) throws Exception { List listWord = new ArrayList(); // 获取词库词语,转化为list FileReader reader = new FileReader("d:/keyWord.txt"); BufferedReader br = new BufferedReader(reader); String s = null; while ((s = br.readLine()) != null) { listWord.add(s.trim()); } br.close(); reader.close(); // **替换脏词 Matcher m = null; for (int i = 0; i < listWord.size(); i++) { Pattern p = Pattern.compile(listWord.get(i).toString(), Pattern.CASE_INSENSITIVE); StringBuffer sb = new StringBuffer(); m = p.matcher(filterText); while (m.find()) { m.appendReplacement(sb, "**"); } m.appendTail(sb); filterText = sb.toString(); } return filterText; } }