2014-02-17 56 views
1

我目前正在用我的「髒字」過濾器找到部分匹配。在java中的字符串匹配

例如:如果我通過在這兩個參數替換字( 「驢」, 「傳球傳球傳給屁股」)

這種方法

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 * SP ** sed的計劃** S

當我真的只是想「路過通過**秒。 有誰知道如何避免使用此方法? 這部分匹配任何幫助將是巨大的感謝!

+1

所以,你想''屁股'前面的一些空白? –

+2

你想看看[Word邊界](http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html) –

回答

3

This tutorial from Oracle應該指出你在正確的方向。

你想在你的模式用一個詞邊界:

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

但請注意,這仍然是有問題的(如褻瀆過濾總是)。定義邊界的「非單詞字符」是[0-9A-Za-z_]

因此例如_ass將不匹配。

你也有褻瀆派生詞......其中術語被預先計劃地說,「洞」,「消滅」的問題,等等

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是值得關注的東西。

0

您也可以使用Matcher類中的replaceAll()方法。它用您指定的替換詞替換所有模式的出現。像下面的東西。

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); 
    }