I'm trying to split a parameter list by regexp.
This is a string with my parameter list:
"a = b, c = 3, d = [1,3,5,7], e, f = g"
What I want is:
["a = b", "c = 3", "d = [1,3,5,7]", "e", "f = g"]
I tried with a lookahead, but Ruby doesn't allow lookbehinds with a dynamic range, so this won't work:
/(?<!\[),(?!\w*\])/
How can I tell the regexp to ignore everything in square brackets?
Maybe something like that would work for you:
str.scan(/(?:\[.*?\]|[^,])+/)
EDIT after second thought.
Simple non-greedy matcher will fail in some cases of nested parentheses.
Rather than trying to get it all done with one splitting regex, you could split, then correct your array of pairs.
input = "a = b, c = 3, d = [1,5], e = f"
pairs = input.split(/,\s*/)
pairs.each_with_index do |item, index|
if index > 0 && (item =~ /=/).nil?
pairs[index - 1] += ',' + item
pairs[index] = nil
end
end
pairs.delete_if { |item| item.nil? }
puts pairs
Outputs:
a = b
c = 3
d = [1,5]
e = f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With