欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

过滤敏感字

程序员文章站 2022-07-12 19:11:19
...

首先需要在src目录下配置需要过滤字符的属性文件:words.properties

package com.zou.regex;
/*
 * 过滤敏感字
 */
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Test2 
{
 private static Pattern pattern = null;
 // 从words.properties初始化正则表达式字符串
 private static void initPattern()
 {
  StringBuffer patternBuf = new StringBuffer("");
  try
  {
   InputStream in = Test2.class.getClassLoader().getResourceAsStream("words.properties");
   Properties pro = new Properties();
   pro.load(in);
   Enumeration enu = pro.propertyNames(); 
   patternBuf.append("(");
   while(enu.hasMoreElements())
   {
    patternBuf.append((String)enu.nextElement()+"|");
   }
   patternBuf.deleteCharAt(patternBuf.length()-1);
   patternBuf.append(")");
  System.out.println(patternBuf.toString());
//unix换成UTF-8
   //pattern = Pattern.compile(new String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));
//win下换成gb2312
   pattern = Pattern.compile(patternBuf.toString());
  }
  catch(IOException ioEx)
  {
   ioEx.printStackTrace();
  }
 }
 private static String doFilter(String str)
 {
  Matcher m = pattern.matcher(str);
  str = m.replaceAll("**");
  return str;
 }
 
 public static void main(String[] args)
 {
  String str = "敏感字敏感字敏感字fd走少fd敏感字敏感字gdf走gfg少";
  System.out.println("str:"+str);
  initPattern();
  Date d1 = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss:SSS Z");
  System.out.println("start:"+formatter.format(d1));
  System.out.println("共"+str.length()+"个字符,查到" + Test2.doFilter(str));
  Date d2 = new Date();
  System.out.println("end:"+formatter.format(d2));
 }
}