Odd string split in ruby? -
i have expression "1=2,3=(4=5,6=7)" , want create hash out of - 1 => 2, 3 => (4=5,6=7). can in 2 passes. in first pass, can transform (.*) (4;5,6;7) , in 2nd pass split.
any better solutions?
as long don't need worry nested parentheses, , inside parentheses treated plain string:
str = "1=2,3=(4=5,6=7)" hash[str.scan(/([^=,]+)=(\([^\)]+\)|[^=,]+)/)] # => {"1"=>"2", "3"=>"(4=5,6=7)"}
if need nested hashes, use recursive method:
def hashify(str) arr = str.scan(/([^=,]+)=(\([^\)]+\)|[^=,]+)/).map |key, val| if val[0] == '(' && val[-1] == ')' [key, hashify(val[1..-2])] else [key, val] end end hash[arr] end hashify "1=2,3=(4=5,6=7)" # => {"1"=>"2", "3"=>{"4"=>"5", "6"=>"7"}}
note still doesn't handle nested parentheses properly. need proper parser that.
Comments
Post a Comment