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?
Asked
Active
Viewed 79 times
-1
-
2Use Pattern.quote in general case, or "\\\[aabb\\\]" for your particular case. – Alex Sveshnikov Mar 17 '21 at 21:06
-
4Does this answer your question? [Escaping special characters in Java Regular Expressions](https://stackoverflow.com/questions/10664434/escaping-special-characters-in-java-regular-expressions) – Janez Kuhar Mar 17 '21 at 21:07
-
2use `str.replace()` instead of `str.replaceAll()` – TruVortex_07 Mar 17 '21 at 21:12
3 Answers
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