Case-insensitive replaceAll in Java
The replaceAll function in the java.lang.String class replaces each substring found in that matches the regular expression to replace.
String sentence = "The sly brown fox jumped over the lazy fox."; String result = sentence.replaceAll("fox", "doggie"); System.out.println("Input: " + sentence); System.out.println("Output: " + result);
Would output:
Input: The sly brown fox jumped over the lazy fox.
Output: The sly brown doggie jumped over the lazy doggie.
However there are cases where we want to replaceall substrings and ignore the case, or make it case insensitive.
String sentence = "The sly brown Fox jumped over the lazy foX."; String result = sentence.replaceAll("fox", "dog"); System.out.println("Input: " + sentence); System.out.println("Output: " + result);
Input: The sly brown Fox jumped over the lazy foX.
Output: The sly brown Fox jumped over the lazy foX.
To create the case sensitive version of replaceAll we do not need to create a new wrapper function or create a utility class somewhere. All we need to do is prepend the Case-insensitve pattern modifier (?i) before our regex to indicate that we don’t care about the case sensitivity of the regex.
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);
Input: The sly brown Fox jumped over the lazy foX.
Output: The sly brown dog jumped over the lazy dog.
Hi! It doesn’t work with accents … :/
Try: Águia
I consider this a bug.
Do you know some workaround?
If you have $ sign in your sentence it wouldn’t work.
like
String sentence = “The sly brown Fox jumped$ over the lazy foX.”;
Hello Shahin,
I added a $ to my example string and the replaceAll still worked.
foi CELSO
But… he eats space char after the replaced “termo”
Hello Celso,
I had a hard time trying to follow what exactly you’re trying to do here so I’ll make a few quick assumptions. I’m assuming that you don’t want to eat the whitespace after the search term.
The regex you have set up now is looking for the term “celso” and one other character that is not a single quote (‘). Because the space character is not a quote the regex matches the term and a single space – then does the replacement. If you were to set the regex to:
String regex = "";Then you’d be matching all variations of celso without the spaces.
However if you just wanted to match the WORD “celso”, and not part of another word of a mistype (such as “celsOOOOO” which would turn into “OOOO”) you can use the word boundary regex:
String regex = "\\b";I hope I helped.