How to replace case-insensitive literal substrings in Java

The Solution to How to replace case-insensitive literal substrings in Java is


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.

~ Answered on 2011-02-20 03:23:35


Most Viewed Questions: