The core String class does not provide replace all method with ignore case.
I have written a method replaceAllIgnoreCase().This method take three parameter as:
/** * @param original: Original string to be modified. Must not be null. * @param regex: String to be discarded. * @param replacement: String to be replaced with. * @return */
This is ready to use method copy class to your project and call method as:
<p style="text-align: center;"><code> . . . String result=EString.replaceAllIgnoreCase(org,regex,replacement); . . .
Here is source code:
/** * * @author [email protected] * @publish @ playjava.wordpress.com * */ public class EString { public static void main(String[] args) { String test = "SUN Rise and sun Set."; String result = replaceAllIgnoreCase(test, "SUN", "Moon"); System.out.println("Original String :" + test); System.out.println("Result String :" + result); } /** * @param original: Original string to be modified. Must not be null. * @param regex: String to be discarded. * @param replacement: String to be replaced with. * @return */ static String replaceAllIgnoreCase(String original, String regex, String replacement) { String r = null; int repl = replacement.length(); int regl = regex.length(); int dif = repl - regl; int cnt = 0; String regLc = regex.toLowerCase(); String repLC = replacement.toLowerCase(); String buf = original.toLowerCase(); int index; while ((index = buf.indexOf(regLc)) >= 0) { buf = buf.substring(index + regl); if (r != null) { if (dif == 0) { r += original.substring(r.length() + dif, r.length() + dif + index); r += replacement; } else { r += original.substring(r.length() - (dif * cnt), r.length() - (dif * cnt) + index); r += replacement; cnt++; } } else { if (index != 0) { r = original.substring(0, index) + replacement; cnt++; } else { r = replacement; cnt++; } } } if(dif==0) { r += original.substring(r.length() + dif, original.length()); } else { r += original.substring(r.length() - (dif * cnt),original.length()); } return r; } }
Share your experience and any bug or performance issue if detected.
One other option is provided as:
String sentence = "The sly brown Fox jumped over the lazy foX.";
String result = sentence.replaceAll("(?i)fox", "dog");
System.out.println("Input: " + sentence);
System.out.println("Output: " + result);
But this was not working all the time for me.