Take the 2-minute tour ×

I'm using

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

to replace "[" symbol in some strings in my text file, but I get:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 7
    at java.util.regex.Pattern.error(Pattern.java:1713)

how can I solve this ?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

The method replaceAll interprets the argument as a regular expression. In a regular expression you must escape [ if you want its literal meaning otherwise it is interpreted as the start of a character class.

str = str.replaceAll("GeoData\\[", "");

If you didn't intend to use a regular expression then use replace instead, as Bozho mentions in his answer.

share|improve this answer
Thanks, one more question: what about the symbol "\" ? Should I use "\\\" ? it seems not working... –  Patrick Feb 20 '11 at 16:16
@Patrick: It's not clear from your question why you are using replaceAll. Perhaps you meant to use replace as Bozho suggests? –  Mark Byers Feb 20 '11 at 16:17
yeah you right. I've actually solved, I was just wondering how to replace the symbol "\" (it is a different question). –  Patrick Feb 20 '11 at 16:20
@Patrick that should be \\\\ you need to escape \ for java strings and for the regular expressions. So \\\\ will effectivly make a string of \\ which the regular expression parser then sees as escaped \ –  DaVinci Feb 20 '11 at 16:26

Use the non-regex method String.replace(..): str.replace("GeoData[", "")

(People tend to miss this method, because it takes a CharSequence as an argument, rather than a String. But String implements CharSequence)

share|improve this answer
+1 This is probably what he wants. –  Mark Byers Feb 20 '11 at 16:17
BTW as a side note: using CharSequence instead of a String is a very good idea when designing an string-intensive API. Users will be grateful if they can use StringBuilder and StringBuffer seamlessly, without the need of explicit toString(). –  Tomasz Nurkiewicz Feb 20 '11 at 16:19

Your Answer


