Abhishek :
I want to replace multiple case insensitive strings from a String.
I could have used: org.apache.commons.lang.StringUtils.replaceEach(text, searchList, replacementList)
but is works for case sensitive strings.
Is there a similar method which works for case insensitive strings?
static String[] old = {"ABHISHEK","Name"};
static String[] nw = {"Abhi","nick name"};
static String s="My name is Abhishek";
System.out.println(StringUtils.replaceEach(s, old, nw));
Output:
My name is Abhishek
Expected:
My nick name is Abhi
Dang Nguyen :
You can try to use regex to archive it
Example
String str = "Dang DANG dAng dang";
//replace all dang(ignore case) with Abhiskek
String result = str.replaceAll("(?i)dang", "Abhiskek");
System.out.println("After replacement:" + " " + result);
Result:
After replacement: Abhiskek Abhiskek Abhiskek Abhiskek
EDIT
String[] old = {"ABHISHEK","Name"};
String[] nw = {"Abhi","nick name"};
String s="My name is Abhishek";
//make sure old and nw have same size please
for(int i =0; i < old.length; i++) {
s = s.replaceAll("(?i)"+old[i], nw[i]);
}
System.out.println(s);
Result:
My nick name is Abhi
Basic ideal: Regex ignore case and replaceAll()
From the comment @flown (Thank you) you need to use
str.replaceAll("(?i)" + Pattern.quote(old[i]), nw[i]);
Because regex treats some special character with a different meaning, ex: .
as any single character
So using the Pattern.quote
will do this.