How to replace case-insensitive literal substrings in Java How to replace case-insensitive literal substrings in Java java java

How to replace case-insensitive literal substrings in Java


String target = "FOOBar";target = target.replaceAll("(?i)foo", "");System.out.println(target);

Output:

Bar

It's worth mentioning that replaceAll treats the first argument as a regex pattern, which can cause unexpected results. To solve this, also use Pattern.quote as suggested in the comments.


If you don't care about case, then you perhaps it doesn't matter if it returns all upcase:

target.toUpperCase().replace("FOO", "");


Not as elegant perhaps as other approaches but it's pretty solid and easy to follow, esp. for people newer to Java. One thing that gets me about the String class is this: It's been around for a very long time and while it supports a global replace with regexp and a global replace with Strings (via CharSequences), that last doesn't have a simple boolean parameter: 'isCaseInsensitive'. Really, you'd've thought that just by adding that one little switch, all the trouble its absence causes for beginners especially could have been avoided. Now on JDK 7, String still doesn't support this one little addition!

Well anyway, I'll stop griping. For everyone in particular newer to Java, here's your cut-and-paste deus ex machina. As I said, not as elegant and won't win you any slick coding prizes, but it works and is reliable. Any comments, feel free to contribute. (Yes, I know, StringBuffer is probably a better choice of managing the two character string mutation lines, but it's easy enough to swap the techniques.)

public String replaceAll(String findtxt, String replacetxt, String str,         boolean isCaseInsensitive) {    if (str == null) {        return null;    }    if (findtxt == null || findtxt.length() == 0) {        return str;    }    if (findtxt.length() > str.length()) {        return str;    }    int counter = 0;    String thesubstr = "";    while ((counter < str.length())             && (str.substring(counter).length() >= findtxt.length())) {        thesubstr = str.substring(counter, counter + findtxt.length());        if (isCaseInsensitive) {            if (thesubstr.equalsIgnoreCase(findtxt)) {                str = str.substring(0, counter) + replacetxt                     + str.substring(counter + findtxt.length());                // Failing to increment counter by replacetxt.length() leaves you open                // to an infinite-replacement loop scenario: Go to replace "a" with "aa" but                // increment counter by only 1 and you'll be replacing 'a's forever.                counter += replacetxt.length();            } else {                counter++; // No match so move on to the next character from                           // which to check for a findtxt string match.            }        } else {            if (thesubstr.equals(findtxt)) {                str = str.substring(0, counter) + replacetxt                     + str.substring(counter + findtxt.length());                counter += replacetxt.length();            } else {                counter++;            }        }    }    return str;}