0

I need to split a string by commas that are outside brackets. I have this string:

'a,b,c,d[a,b,c[a,b]],e'

and my split needs to return:

['a', 'b', 'c', 'd[a,b,c[a,b]]', 'e']

How can I do that?

7
  • 4
    Hey, thanks for asking your first SO question! Welcome. Question. What larger problem are you trying to solve here? Are you interfacing with a system that you can't change? Sometimes when trying to parse complicated strings or syntax the answer can be to solve a different problem. For example, if your data was a valid JSON string, then you could just parse it, manipulate it as an array, and then convert it back to JSON. Commented Mar 1, 2018 at 21:27
  • Have you tryed using regular expressions? Commented Mar 1, 2018 at 21:31
  • Hi Jared, Thanks! Commented Mar 2, 2018 at 11:23
  • Your question is not clear. What do you want to return for 'a,b],c'? Is the comma between a and b inside or outside of the brackets? Or, if it is the case that such string is outside of your consideration, then state what kind of strings are subject to your issue. Commented Mar 2, 2018 at 11:30
  • 1
    sawa, your answer worked for me, its exactly what i'm looking for! Thanks! Commented Mar 2, 2018 at 11:38

1 Answer 1

1
'a,b,c,d[a,b,c[a,b]],e'
.scan(/(?:\[[^\]]*\]|[^,])+/)
# => ["a", "b", "c", "d[a,b,c[a,b]]", "e"]

'a,[a][b],e'
.scan(/(?:\[[^\]]*\]|[^,])+/)
# => ["a", "[a][b]", "e"]
Sign up to request clarification or add additional context in comments.

1 Comment

this answer is much better, I just deleted mine

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.