regex - Ruby convert string to specific array format -


what need convert this:

"id,name,user[id,email]" 

into array:

["id", "name", {"user"=>["id", "email"]}]  

what best way that? think function split or scan can help, don't have knowledge in regex solve this.

just out of curiosity:

▶ str = "id,name,user[id,email]" ▶ eval "[#{str.gsub(/(\w+)\[(.*?)\]/, '{\1=>[\2]}').gsub(/\w+/, ':\0')}]" #⇒ [ #  [0] :id, #  [1] :name, #  [2] { #    :user => [ #      [0] :id, #      [1] :email #    ] #  } #] 

disclamer: use eval in production 1 must understand risks.

upd safe evaling (note every ascii \w symbol converted it’s wide pair utf-8 prevent injection; not best way around, works nicely unless have ruby functions named wide characters):

▶ safe = str.gsub(/\w/) |e|  ▷   e.each_codepoint.map |cp|  ▷     cp + 0xff00 - 0x0020 ▷   end.pack('u') ▷ end #⇒ "id,name,user[id,email]" ▶ eval "[#{safe.gsub(/(\p{l}+)\[(.*?)\]/, '{\1=>[\2]}').gsub(/\p{l}+/, ':\0')}]" #⇒ [ #  [0] :id, #  [1] :name, #  [2] { #    :user => [ #      [0] :id, #      [1] :email #    ] #  } #] 

now free turn keys wide characters ascii.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -