简体   繁体   English

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

[英]Case-insensitive search and replace

I have the following string, how do I search and replace it in Java?我有以下字符串,如何在 Java 中搜索和替换它?

Before

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

After search and replace, it shoud be * animal = Dog and * bird = Peacock搜索替换后,应该是*动物=和*=孔雀

Dog is a Dog and Peacock is a Peacock.

I have tried replacing the occurances this pattern - (?i)\\\\*animal but it doesn't work.我试过替换这种模式的出现 - (?i)\\\\*animal但它不起作用。 What am I doing wrong?我究竟做错了什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM