2

I have strings which look like this: [item 1, item2, item3]

and my desired output is:

item 1
item2
item3

I wrote this code:

String text = "[item 1, item2, item3]";
String[] text_output = text.split(", |\\[|\\]");
for(String item:text_output)
    fileOutStream.write(("\n"+item).getBytes());

and the output I get is correct, with the difference that in the output array the first element is an empty string. What am I doing wrong?

3 Answers 3

3

You have requested to split the string at [ and ] so the system obeys and considers the empty space preceding the [ to be your first element. There are many ways in which you can proceed:

  1. use text.replaceAll("\\[|\\]", "") before splitting;
  2. hardcode the elimination of the first and last char before splitting: text.substring(1, text.length()-1);
  3. use a positive match instead of negative one:

    Pattern.compile("[^,\\[\\]]+").matcher().find()
    
Sign up to request clarification or add additional context in comments.

3 Comments

Is there any way I could modify the regex so that wouldn't happen?
Thanks! Any idea why in my initial code there was no empty element also as the last element in the array? Since [ caused the problem because it was the first character in the String, why didn't ] do the same since it was the last one?
Because that is the default behavior of String.split, as per its Javadoc.
0

That happens when you try to split and the first character is the one you want to split. You should make a new a new array and not select the first element (the null one).

String[] text_output = text.substring(1).split(", |\\[|\\]");

If you want to just remove the first character, you can use that and you will have the output that you want. Just have in mind that that happens when you try to split and the first character is one of the splitting.

Comments

0

First is the empty string coz you're splitting using \\[ also, so first element is [ in your string. Just ignore your first element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.