How to replace case-insensitive literal substrings in Java

J. Lin picture J. Lin · Feb 20, 2011 · Viewed 110.4k times · Source

Using the method replace(CharSequence target, CharSequence replacement) in String, how can I make the target case-insensitive?

For example, the way it works right now:

String target = "FooBar";
target.replace("Foo", "") // would return "Bar"

String target = "fooBar";
target.replace("Foo", "") // would return "fooBar"

How can I make it so replace (or if there is a more suitable method) is case-insensitive so that both examples return "Bar"?

Answer

lukastymo picture lukastymo · Feb 20, 2011
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.