-3

I'm trying to use the java method replaceAll(), that removes from a string all characters that match a given regex, to remove the opening and closing brackets characters from a string.

So, I need to use as a parameter a regex that matches [ and ].

I've tried using [|] or ([|]) but they don't seem to work.

kace91
  • 821
  • 1
  • 10
  • 23
  • 6
    `\[` and `\]`.. This is so basic, it should be in any documentation. – Jongware Oct 17 '14 at 22:24
  • It *is* in the documentation: "[abc] a, b, or c (simple class)" and "\ [...] quotes the following character". – John Bollinger Oct 17 '14 at 22:26
  • 5
    And since you're in Java, you will need to add an extra slash to escape the first slash. :) – Voicu Oct 17 '14 at 22:26
  • In any language, if you need to use the literal representation of a special character, you have to escape it. – Gary Oct 17 '14 at 22:27
  • You can also use Pattern.quote to do the same if you feel like doing a little extra typing. See this question for even more sugar: http://stackoverflow.com/questions/1140268/how-to-escape-a-square-bracket-for-pattern-compilation – MarsAtomic Oct 17 '14 at 22:28

2 Answers2

0

You need to escape them:

 \[ and \]
Alain Collins
  • 16,268
  • 2
  • 32
  • 55
0

This should take off both the opening and closing brackets for you.

str = str.replaceAll("\\[", "").replaceAll("\\]", "");
jhnewkirk
  • 87
  • 9