DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Parse An Argument List Containing A Quoted String

03.23.2010
| 3004 views |
  • submit to reddit
        The following example parses a string containing a quoted string:
s = %q(passed "abc def" etert)
s.gsub!(/\".[^\|\'"]+["']/) {|x| x.gsub(/\s/,'%20')}
a = s.split(/\s/).map {|x| x.gsub(/%20/,' ')}
#=> ["passed", "\"abc def\"", "etert"]

*update: 23-Mar-2010 @ 1:50pm*
Here's how to remove the quotes from the final result:
a = s.split(/\s/).map {|x| x.gsub(/%20/,' ').sub(/\"(.*)\"/,'\1')}
#=> ["passed", "abc def", "etert"]