繁体   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