-1

I want to replace a string "[aabb]" in a txt file, but if I wanted to use replaceAll("[aabb]", "x"); method for this replacement, java sees that as a regular expression. How can I escape "[aabb]" string?

3 Answers3

3

Try one of these -

Pattern.quote("[aabb]")

OR make the string "\\Q[aabb]\\E" [remember \ needs to be quoted for Java strings].

As well as lots of great answers on SO - go to the javadoc for Pattern

Mr R
  • 754
  • 7
  • 19
2

You need to escape [ and ] as they are the meta-characters used to specify character classes i.e. if you do not escape them, the regex engine will treat [aabb] as one of the characters within the square bracket.

Demo:

public class Main {
    public static void main(String[] args) {
        String str = "Hello [aabb] World";
        str = str.replaceAll("\\[aabb\\]", "x");
        System.out.println(str);
    }
}

Output:

Hello x World
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2

You can use replaceAll(Pattern.quote("[aabb]"),"x")

Frightera
  • 4,773
  • 2
  • 13
  • 28
olz
  • 116
  • 1
  • 3