以下实现对关键字的过滤:
1、words.properties配置关键字的配置文件;内容如下:
name1
name2
name3
2、KeyFilter.java:
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 KeyFilter
{
private static Pattern pattern = null;
// 从words.properties初始化正则表达式字符串
private static void initPattern() {
StringBuffer patternBuffer = new StringBuffer();
try {
InputStream in = KeyFilter.class.getClassLoader().getResourceAsStream("words.properties");
Properties property = new Properties();
property.load(in);
Enumeration enu = property.propertyNames();
patternBuffer.append("(");
while (enu.hasMoreElements()) {
String scontent = (String) enu.nextElement();
patternBuffer.append(scontent + "|");
System.out.println(scontent);
}
patternBuffer.deleteCharAt(patternBuffer.length() - 1);
patternBuffer.append(")");
// 装换编码
pattern = Pattern.compile(patternBuffer.toString());
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
private static String doFilter(String str) {
initPattern();
Matcher m = pattern.matcher(str);
// 选择替换方式,这里以* 号代替
str = m.replaceAll("*");
return str;
}
public static void main(String[] args) {
String str = "我日,艹,fuck,你妹的 干啥呢";
System.out.println(doFilter(str));
}