到目前为止,我已经能够审查“猫”,“狗”和“骆驼”。现在我只需要让“教条”成为例外,但我终生也搞不懂它。下面我附上了我到目前为止所拥有的。请提供任何建议,真的会很有帮助。
/* take userinput and determine if it contains profanity
* if userinput contains profanity, it will be filtered
* and a new sentence will be generated with the word censored
*/
keyboard = new Scanner(System.in);
System.out.println("Welcome to the Star Bulletin Board!");
System.out.println("Generate your first post below!");
String userInput = keyboard.nextLine();
userInput = userInput.toLowerCase();
if (userInput.indexOf("cat") != 15){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("cat", "***"));
}
else
System.out.println(userInput);
if (userInput.indexOf("dog") != -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("dog", "***"));
}
if (userInput.indexOf("llama")!= -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("llama", "*****"));
}发布于 2015-05-29 00:45:14
您可以使用单词边界\\b。单词边界与单词的边缘相匹配,如空格或标点符号。
if (userInput.matches(".*\\bdog\\b.*")) {
userInput = userInput.replaceAll("\\bdog\\b", "***");
}这将审查“不要成为一头骆驼”。但它不会审查“不要教条主义”。
userInput.matches(".*\\bdog\\b.*")是一种比indexOf/contains稍好的条件,因为它与替换项具有相同的匹配项。尽管没有审查任何内容,indexOf/contains仍会显示该消息。.*可以选择性地匹配任何字符(通常是换行符除外)。
注意:这仍然不是一种非常有效的过滤脏话的方法。参见http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/。
发布于 2015-05-29 00:52:53
使用单词边界。看一下下面的代码;它将为除最后一个案例之外的所有案例输出true:
String a = "what you there";
String b = "yes what there";
String c = "yes there what";
String d = "whatabout this";
System.out.println(Pattern.compile("\\bwhat\\b").matcher(a).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(b).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(c).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(d).find());您可以将所有不好的单词组合成一个正则表达式,如下所示:
Pattern filter = Pattern.compile("\\b(cat|llama|dog)\\b");这对于简单的情况很好,但是对于更健壮的解决方案,您可能希望使用库。有关更多信息,请查看this question。
https://stackoverflow.com/questions/30512345
复制相似问题