不区分大小写的搜索和替换

时间:2011-11-06 04:51:41

标签: java regex string search replace

我有以下字符串,如何在Java中搜索和替换它?

之前

*animal is a *ANImal and *Bird is a *bIrd.

搜索和替换后,它应该 * 动物 = 和* = 孔雀

Dog is a Dog and Peacock is a Peacock.

我尝试用这种模式替换出现 - (?i)\\ * animal 但它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

   public String replaceStrPattern(String str, String pattern, String replaceWith) {

            String newStr = str;
            String nonAlphaNumeric = "[^a-zA-Z0-9]";

    String[] words = str.split(" ");
    for(String word : words) {
               word = word.replaceAll(nonAlphaNumeric, "").trim();
        if(word.equalsIgnoreCase(pattern))
            newStr = newStr.replace(word, replaceWith);
    }

        return newStr;      
}