Pravat Panda
Pravat Panda

Reputation: 1090

split string based on comma delimiter

what is wrong in the following code?

String selectedCountriesStr = countries.replaceAll("[", "").replaceAll("]", "").trim();
String[] selectedCountriesArr = selectedCountriesStr.split(",");

Input String [10000,20000,304050,766666]

Getting error java.util.regex.PatternSyntaxException: Unclosed character class near index 0

Upvotes: 1

Views: 6697

Answers (3)

jlordo
jlordo

Reputation: 37813

You have to escape square brackets because replaceAll() interprets the first argument as a regular expression:

replaceAll("\\[", "")
            ^^

because, as the error message tells you, the are used for character classes in a regex. Double backslashes are necessary, because "\[" would be an invalid escape sequence. Since the backslash is escaped, the regex engine only receives one backslash.

Also, you can use

replace("[", "")

it will also replace all occurrences of the given CharSequence as is.

You can read more about it in JavaDoc.

Upvotes: 8

Rachita Nanda
Rachita Nanda

Reputation: 4659

     String str = "hi,hello,abc,example,problems";
    String[] splits = str.split(",");

    System.out.println("splits.size: " + splits.length);

    for(String asset: splits){
    System.out.println(asset);

    }

Split function will easily split your string like this

Upvotes: -1

fge
fge

Reputation: 121712

Brackets are regex metacharacters, you need to prefix them with a backslash:

.replaceAll("\\[", "").replaceAll("\\]", "")

Also, since this is a simple string substitution, you'd better use .replace():

.replace("[", "").replace("]", "")

Upvotes: 6

Related Questions