简体   繁体   中英

Case-insensitive search and replace

I have the following string, how do I search and replace it in 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. 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;      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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