我有一个类检查id短语包含在一条消息中,我试图用Matcher
和Pattern
和String.contains()
来做,但返回的结果很奇怪。检查一条消息是否包含一个字符串
这里是类:
public class MotsClesFilter implements EmailFilter {
final String NAME = "Filtrage par mots cles";
/*private Pattern chaineSpam;
private Matcher chaineCourriel;*/
private int nbOccMotSpam;
private byte confidenceLevel;
@Override
public String getFilterName() {
return this.NAME;
}
@Override
public byte checkSpam(MimeMessage message) {
analyze(message);
if(this.nbOccMotSpam==0)
this.confidenceLevel = 1;
else if (this.nbOccMotSpam>0 && this.nbOccMotSpam<2)
this.confidenceLevel = CANT_SAY;
else if (this.nbOccMotSpam>1 && this.nbOccMotSpam<3)
this.confidenceLevel = 50;
else if (this.nbOccMotSpam>3 && this.nbOccMotSpam<4)
this.confidenceLevel = 65;
else if (this.nbOccMotSpam>4 && this.nbOccMotSpam<5)
this.confidenceLevel = 85;
else this.confidenceLevel = 90;
return (getConfidenceLevel());
}
public void analyze(MimeMessage message){
try {
List<String> listeChaines = new ArrayList<String>();
BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File("SpamWords.txt"))));
while(bis.ready()){
String ligne = bis.readLine();
listeChaines.add(ligne);
}
String mail = ((String.valueOf(message.getContent())));
//System.out.println(mail);
for (int j =0; j<listeChaines.size();j++){
//System.out.println(listeChaines.get(j));
Pattern chaineSpam = Pattern.compile(listeChaines.get(j),Pattern.CASE_INSENSITIVE);
Matcher chaineCourriel = chaineSpam.matcher(mail);
if (chaineCourriel.matches())
this.nbOccMotSpam++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public byte getConfidenceLevel() {
// TODO Auto-generated method stub
return this.confidenceLevel;
}
@Override
public boolean enabled() {
// TODO Auto-generated method stub
return true;
}
}
通过checkSpam
返回的结果总是1场,如果使用比赛和90,如果我使用发现,它也返回90,当我使用mail.contains(listeChaines.get(j))
。
这两种方法都是有效的,你必须尽可能小心Pattern和Matcher 'String'中有非正则表达式兼容的字符。 “Contains”是一个更好的选择。也许添加一些日志记录并使用调试器来查看发生了什么。也用于从'BufferedReader'阅读常规成语是'如果((行= reader.readLine())!= null'。 – 2013-04-08 21:27:28
我推荐使用'之开关语句,而不是那些'if'语句。此外,还有有两个'if'语句永远不会为真。 – 2013-04-08 21:29:12
这如果是从来没有真的吗?我想包含但它就像发现,它不是给我正确的结果。 – user2133558 2013-04-08 21:36:35