2

I want to replace a part of a string with another string. For example, a string comes in, and it contains meat, but I want it to change that meat to vegetable. I know I can do this with the following statement.

str = str.replaceAll("meat", "vegetable");

However, I need to have the exact capitalization. I'm looking for a way to do this no matter what letters are upper or lowercase in the example meat.

My application is a filter for Minecraft. Either swears, or just customizing the menu. Like I'd like to replace every instance of the word minecraft, no matter the capitalization, to say Best game Ever!!.

I have modded it so that it can recognize and replace specific capitalizations, but that is very limiting.

I hope I have supplied enough info so that someone can help me with this.

3 Answers3

10

You can make regex case-insensitive by adding (?i) flag at start

str = str.replaceAll("(?i)meat", "vegatable");

example

System.out.println("aBc def".replaceAll("(?i)abc","X")); // out: "X def" 
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • How do I perform on more complex replacements? Like, replace Math.sin(30) with Math.sin(Math.toDegrees(30)) in a complete expression string. – Sharjith N. Jul 19 '15 at 16:35
  • 1
    @SharjithN. You can try to reuse part from capturing group `replaceAll("Math\\.sin\\((\\d+)\\)", "Math.sin(Math.toDegrees($1))")` – Pshemo Jul 19 '15 at 17:06
  • 1
    @SharjithN. But if you would like to do some more complex replacement like replace some number with its incremented value you would need to use Matcher class and its `appendReplacement` and `appendTail`. Here you have example http://stackoverflow.com/a/19645633/1393766 – Pshemo Jul 19 '15 at 17:13
  • Thank you @Pshemo. That worked for me. The regex backreference substitution. – Sharjith N. Jul 22 '15 at 11:40
4

The first argument to replaceAll is a regular expression, and you can embed a flag in the expression to make it case-insensitive:

str = str.replaceAll("(?i)meat", "vegatable");
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
4

Another way: Here the flag is not explicitly in the regex, but passed as a separate parameter.

String input = "abc MeAt def";
Pattern pattern = Pattern.compile("meat", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
String output = matcher.replaceAll("vegetable");
System.out.println(output);
jlordo
  • 37,490
  • 6
  • 58
  • 83