到目前为止,我已经能够审查“猫”,“狗”和“美洲驼”。现在,我只需要将“ Dogmatic”作为例外,但无法在我的一生中解决它。下面附上我到目前为止的内容。请任何建议将真正帮助。

/* 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", "*****"));
}

最佳答案

您可以使用单词边界\\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/

关于java - 亵渎过滤器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30512345/

10-15 16:21