SummerFlower
SummerFlower

Reputation: 25

Java - Split strings by "]"

I have a string, that looks like this: [apple, peach, plum]. I want to split it by "[" and "]" to get the items of the "list", but it doesn't work with this solution:

String string = "[apple, peach, plum]";
String splitted = (string.split(Pattern.quote("["))[1]).split(Pattern.quote("]"))[0];

The first split is working, but when I try to split it by the "]", it doesn't do anything.

(I've tried this:

String splitted = (string.split(Pattern.quote("["))[1]).split(Pattern.quote(","))[0];

and it worked, so I think the problem is the "]" sign.)

Any idea?

Upvotes: 0

Views: 82

Answers (2)

Tuco
Tuco

Reputation: 513

You can also use a Pattern + Matcher with regex \\s*(\\[)?([^,]*)(\\])?\\s*:

        Pattern pat = Pattern.compile("\\s*(\\[)?([^,]*)(\\])?\\s*");
        Matcher m = pat.matcher(string);
        m.find();
        System.out.println(m.group(2));
        m.find();
        System.out.println(m.group(2));
        ...

The pattern takes all that is delimited by a comma (([^,]+)) and that can begin by a [ ((\[)?) and ends by (\])?.

Upvotes: 0

Mena
Mena

Reputation: 48404

You don't actually want to split by the square brackets, you just want to eliminate them and split by comma.

If your input is consistent, you could use the following idiom:

String string = "[apple, peach, plum]";
System.out.println(
    // Array String representation
    Arrays.toString(
        // removing square brackets
        string.substring(1, string.length() - 1)
        // splitting by comma + optional whitespace
        .split(",\\s*")
    )
);

Output (note this is a String array consisting of your items)

[apple, peach, plum]

Upvotes: 2

Related Questions