Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: replace "[" "]" from text files strings

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
GeoData[
       ^
    at java.util.regex.Pattern.error(Pattern.java:1713)

how can I solve this ?

like image 764
aneuryzm Avatar asked Feb 20 '11 16:02

aneuryzm


2 Answers

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.

like image 156
Mark Byers Avatar answered Oct 20 '22 17:10

Mark Byers


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)

like image 29
Bozho Avatar answered Oct 20 '22 18:10

Bozho