I am attempting to split the ORDER BY statement of a SQL query into an array. First inclination is:
order_by.split(',')
but that does not work for order by statements like the following:
SUBSTRING('test',1,3) ASC, SUBSTRING('test2', 2,2 ) DESC
The desired output for the above statement would be:
["SUBSTRING('test',1,3) ASC", "SUBSTRING('test2', 2,2 ) DESC"]
I am fairly certain that it would work if I could match any comma that is not enclosed in parethesis, but I cannot find a way to do that in ruby regex because lookbehind is not supported.
While I suspect there probably is still a way of doing it with regex, you can do it with simple string parsing as well.
Find all commas in the string, then go forwards or backwards from that point (it won’t matter which if the brackets are balanced correctly), adding one for an open brace and subtracting one for a closed brace. If you don’t have 0 at the end, you’re inside a brace, so it’s not a comma you want.
Split on all other commas.
EDIT
Although the comment about this methodology failing in the case of parentheses enclosed in commas is valid, it may be the case that you’re dealing with queries simple enough not to worry about that. If that is the case, this should work: