java中的字符串匹配

时间:2014-02-17 21:21:27

标签: java string string-matching

我目前正在努力寻找部分匹配的“脏词”过滤器。

示例:如果我传入这两个参数replaceWord(“屁股”,“传球传递屁股”)

这个方法

private static String replaceWord(String word, String input) {
    Pattern legacyPattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
    Matcher matcher = legacyPattern.matcher(input);
    StringBuilder returnString = new StringBuilder();
    int index = 0;
    while(matcher.find()) {
        returnString.append(input.substring(index,matcher.start()));
        for(int i = 0; i < word.length() - 1; i++) {
            returnString.append('*');
        }
        returnString.append(word.substring(word.length()-1));

        index = matcher.end();
    }
    if(index < input.length() - 1){
        returnString.append(input.substring(index));
    }
    return returnString.toString();
}

我得到p * 唱p * s p ** sed ** s

当我真的只想要“传球传球**时。 有谁知道如何避免这种方法的部分匹配? 任何帮助都会非常感谢!

3 个答案:

答案 0 :(得分:3)

This tutorial from Oracle应该指出正确的方向。

您想在模式中使用单词边界:

Pattern p = Pattern.compile("\\bword\\b", Pattern.CASE_INSENSITIVE);

但请注意,这仍然存在问题(因为亵渎过滤总是如此)。定义边界的“非单词字符”是[0-9A-Za-z_]

中未包含的任何内容

例如,_ass不匹配。

你也有亵渎派生词的问题......这个词的前提是说“洞”,“擦”等等

答案 1 :(得分:0)

我正在处理一个脏字过滤器,我选择使用的选项是Soundex和一些正则表达式。

我首先使用\ w过滤出奇怪的字符,即[a-zA-Z_0-9]。

然后使用soundex(String)创建一个字符串,您可以根据要测试的单词的soundex字符串进行检查。

 String soundExOfDirtyWord = Soundex.soundex(dirtyWord);
 String soundExOfTestWord = Soundex.soundex(testWord);
 if (soundExOfTestWord.equals(soundExOfDirtyWord)) {
     System.out.println("The test words sounds like " + dirtyWord);
 }

我只是在程序中保留一个脏字列表,让SoundEx通过它们来检查。 algorithm值得一看。

答案 2 :(得分:0)

您还可以使用replaceAll()课程中的Matcher方法。它用您指定的替换单词替换模式的所有出现。像下面的东西。

    private static String replaceWord(String word, String input) {
        Pattern legacyPattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE);
        Matcher matcher = legacyPattern.matcher(input);
        String replacement = "";
        for (int i = 0; i < word.length() - 1; i++) {
           replacement += "*";
        }
        replacement += word.charAt(word.length() - 1);
        return matcher.replaceAll(replacement);
    }