簡體   English   中英

如何使以下正則表達式與我的審查員匹配? 爪哇

[英]How can I make the following regex match my censors? Java

我正在嘗試檢查應用程序中的特定字符串和模式,但是在搜索模式時,匹配器似乎未找到任何結果。

public String censorString(String s) {
        System.out.println("Censoring... "+ s);
        if (findPatterns(s)) {
            System.out.println("Found pattern");
            for (String censor : foundPatterns) {
                for (int i = 0; i < censor.length(); i++) 
                    s.replace(censor.charAt(i), (char)42);
            }
        }
        return s;
    }

    public boolean findPatterns(String s) {
        for (String censor : censoredWords) {
            Pattern p = Pattern.compile("(.*)["+censor+"](.*)");//regex
            Matcher m = p.matcher(s);
            while (m.find()) {
                foundPatterns.add(censor);
                return true;
            }
        }
        return false;
    }

目前,如果在字符串中找到了檢查器,我將只關注一種模式。 我嘗試了許多組合,但似乎都沒有返回“ true”。

"(.*)["+censor+"](.*)"
"(.*)["+censor+"]"
"["+censor+"]"
"["+censor+"]+"

任何幫助,將不勝感激。

用法:我檢查的單詞是“你好”,“再見”

String s = "hello there, today is a fine day."
System.out.println(censorString(s));

應該打印" ***** today is a fine day. "

您的正則表達式是正確的! 問題在這里。

s.replace(censor.charAt(i), (char)42);

如果您希望此行重寫字符串的檢查部分,則不會。 請檢查Java文檔中的字符串。

請在下面的程序中找到將要執行的操作。 我刪除了您的findpattern方法,並在String API中僅使用了帶有正則表達式的replaceall。 希望這可以幫助。

公共類Regex_SO {

private String[] censoredWords = new String[]{"hello"};

 /**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Regex_SO regex_SO = new Regex_SO();
    regex_SO.censorString("hello there, today is a fine day. hello again");
}

public String censorString(String s) {
    System.out.println("Censoring... "+ s);

    for(String censoredWord : censoredWords){
        String replaceStr = "";
        for(int index = 0; index < censoredWord.length();index++){
            replaceStr = replaceStr + "*";
        }

       s =  s.replaceAll(censoredWord, replaceStr);
    }
    System.out.println("Censored String is .. " + s);
    return s;
}

}

由於這似乎是家庭作業,因此我無法為您提供工作代碼,但是這里有一些指針

  • 考慮使用\\\\b(word1|word2|word3)\\\\b正則表達式查找特定單詞
  • 要創建表示* char ,可以將其寫為'*' 不要使用(char)42來避免出現幻數
  • 創建新字符串,其長度與舊字符串相同,但僅填充特定字符,您可以使用String newString = oldString.replaceAll(".","*")
  • 要用新值替換即時創建的匹配項,可以使用Matcher類中的appendReplacementappendTail方法。 這是使用它的代碼的樣子

     StringBuffer sb = new StringBuffer();//buffer for string with replaced values Pattern p = Pattern.compile(yourRegex); Matcher m = p.matcher(yourText); while (m.find()){ String match = m.group(); //this will represent current match String newValue = ...; //here you need to decide how to replace it m.appentReplacemenet(sb, newValue ); } m.appendTail(sb); String censoredString = sb.toString(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM