关键字查询,在web开发中,可能应用到的场景:
建立***.properties 文件,文件中写入关键字。例如itil中常用的:服务器,路由器......
传入的参数往往是用户在客户端输入的内容。当作
doFilter(String str)方法中的参数str。
一下的代码能够匹配出客户输入的信息中所含的关键字
m.group()
,用作查询,统计等相关功能。
public class KeyWordFilter {
private static Pattern pattern = null;
StringBuffer patternBuf = new StringBuffer("");
try {
FileInputStream in = new FileInputStream("words/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(")");
// unix换成UTF-8
// pattern = Pattern.compile(new
// String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));
// win下换成gb2312
//pattern = Pattern.compile(new String(patternBuf.toString()
// .getBytes("ISO-8859-1"), "gb2312"));
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
public static String doFilter(String str) {
Matcher m = pattern.matcher(str);
while (m.find())//查找符合pattern的字符串
return str;
}
public static void main(String[] args) throws IOException{
KeyWordFilter.initPattern();
KeyWordFilter.doFilter("从前有一个小孩");
}