[java] Java replace all square brackets in a string

I want to remove square brackets from a string, but I don't know how.

String str = "[Chrissman-@1]";
str = replaceAll("\\[\\]", "");

String[] temp = str.split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);

But my result is: [Chrissman | 1] The square brackets doesn't get removed.

I tried using a different regex: "\\[.*?\\]", "\\[\\d+\\]" but the result is the same, the square brackets still attached on the string.

Edit:

I tried:

str.replaceAll("]", "");
str.replaceAll("[", "");

And now I'm getting:

Exception in thread "Thread-4" 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)

This question is related to java regex string split

The answer is


You're currently trying to remove the exact string [] - two square brackets with nothing between them. Instead, you want to remove all [ and separately remove all ].

Personally I would avoid using replaceAll here as it introduces more confusion due to the regex part - I'd use:

String replaced = original.replace("[", "").replace("]", "");

Only use the methods which take regular expressions if you really want to do full pattern matching. When you just want to replace all occurrences of a fixed string, replace is simpler to read and understand.

(There are alternative approaches which use the regular expression form and really match patterns, but I think the above code is significantly simpler.)


Your regex matches (and removes) only subsequent square brackets. Use this instead:

str = str.replaceAll("\\[|\\]", "");

If you only want to replace bracket pairs with content in between, you could use this:

str = str.replaceAll("\\[(.*?)\\]", "$1");

_x000D_
_x000D_
   Use this line:) String result = strCurBal.replaceAll("[(" what ever u need to remove ")]", "");_x000D_
_x000D_
    String strCurBal = "(+)3428";_x000D_
    Log.e("Agilanbu before omit ", strCurBal);_x000D_
    String result = strCurBal.replaceAll("[()]", ""); // () removing special characters from string_x000D_
    Log.e("Agilanbu after omit ", result);_x000D_
   _x000D_
    o/p :_x000D_
    Agilanbu before omit : (+)3428_x000D_
    Agilanbu after omit :  +3428_x000D_
_x000D_
    String finalVal = result.replaceAll("[+]", ""); // + removing special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal);_x000D_
    o/p_x000D_
    Agilanbu finalVal : 3428_x000D_
            _x000D_
    String finalVal1 = result.replaceAll("[+]", "-"); // insert | append | replace the special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal1);_x000D_
    o/p_x000D_
    Agilanbu finalVal : -3428  // replacing the + symbol to -
_x000D_
_x000D_
_x000D_


You may also do it like this:

String data = "[yourdata]";
String regex = "\\[|\\]";
data  = data .replaceAll(regex, "");
System.out.println(data);

String str, str1;
Scanner sc = new Scanner(System.in);

System.out.print("Enter a String : ");
str = sc.nextLine();


str1 = str.replaceAll("[aeiouAEIOU]", "");



System.out.print(str1);

use regex [\\[\\]] -

String str = "[Chrissman-@1]";
String[] temp = str.replaceAll("[\\[\\]]", "").split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);

output -

Nickname: Chrissman | Power: 1

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows