首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >脏话过滤器

脏话过滤器
EN

Stack Overflow用户
提问于 2015-05-29 00:36:08
回答 2查看 1.5K关注 0票数 1

到目前为止,我已经能够审查“猫”,“狗”和“骆驼”。现在我只需要让“教条”成为例外,但我终生也搞不懂它。下面我附上了我到目前为止所拥有的。请提供任何建议,真的会很有帮助。

代码语言:javascript
复制
/* 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", "*****"));
}
EN

回答 2

Stack Overflow用户

发布于 2015-05-29 00:45:14

您可以使用单词边界\\b。单词边界与单词的边缘相匹配,如空格或标点符号。

代码语言:javascript
复制
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/

票数 4
EN

Stack Overflow用户

发布于 2015-05-29 00:52:53

使用单词边界。看一下下面的代码;它将为除最后一个案例之外的所有案例输出true

代码语言:javascript
复制
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());

您可以将所有不好的单词组合成一个正则表达式,如下所示:

代码语言:javascript
复制
Pattern filter = Pattern.compile("\\b(cat|llama|dog)\\b");

这对于简单的情况很好,但是对于更健壮的解决方案,您可能希望使用库。有关更多信息,请查看this question

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30512345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档