By default, the #split
method work as follows:
"id,name,title(first_name,last_name)".split(",")
will give you following output:
["id", "name", "title(first_name", "last_name)"]
But I want something like following:
["id", "name", "title(first_name,last_name)"]
So, I use following regex (from the this answer) using split to get desired output:
"id,name,title(first_name,last_name)".split(/,(?![^(]*\))/)
But, again when I use another string, which is my actual input above, the logic fails. My actual string is:
"id,name,title(first_name,last_name,address(street,pincode(id,code)))"
and it is giving following output:
["id", "name", "title(first_name", "last_name", "address(street", "pincode(id,code)))"]
rather than
["id", "name", "title(first_name,last_name,address(street,pincode(id,code)))"]
A comma is to be split upon if and only if
stack
is zero when it is encountered. If it is to be split upon it is changed to a character (split_here
) that is not in the string. (I used0.chr
). The string is then split onsplit_here
.This could be one approach:
Creating a duplicate string and splitting them both, then combining the first two elements of the first string with the joined last two elements of the second string copy. At least in this specific scenario it would give you the desired result.
Updated Answer
Since the earlier answer didn't take care of all the cases as rightly pointed out in the comments, I'm updating the answer with another solution.
This approach separates the valid commas using a separator
|
and, later uses it to split the string usingString#split
.I'm sure this can be optimized more.