'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?
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
