I am trying to replace all square brackets i my string .
This is my program
package com;
import java.util.ArrayList;
import org.apache.commons.
String.replaceAll
takes a regular expression pattern, but you don't need regular expressions at all. You can use:
str = str.replace("[", "").replace("]", "");
Or you could use a regex if you wanted, replacing both in one go:
str = str.replaceAll("[\\[\\]]", "");
That's saying "replace any character in the set (open square bracket, close square bracket) with the empty string. The \\
is to escape the square brackets within the set.
Note that you need to use the result of replace
(or replaceAll
) - strings are immutable in Java, so any methods like replace
don't modify the existing string, they return a reference to a new string with the relevant modifications.