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.lang3.StringUtils;
import org.json.JSONException;
public class Teste {
/**
* @param args
* @throws JSONException
*/
public static void main(String[] args) throws JSONException {
String str = "[Fountain#Apple#Big(7)]";
str.replaceAll("[", "").replace("]", "");
System.out.println(str);
}
}
But i am getting
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.clazz(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at com.Teste.main(Teste.java:19)
Could anybody please tell me how to replace all square brackets ??
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.
See more on this question at Stackoverflow