Galet
Galet

Reputation: 6309

Split String into array of values

Input String:-

str = '"2014-09-04 21:12:05" 5469687123030383463 192.168.1.2 4 7879 0 43 "www.test.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36" 404 123 F 21549 50 0 - Test1

When i split with whitespaces:-

str.split(' ')

 => ["\"2014-09-04", "21:12:05\"", "5469687123030383463", "192.168.1.2", "4", "7879", "0", "43", "\"www.test.com/\"", "\"Mozilla/5.0", "(X11;", "Linux", "x86_64)", "AppleWebKit/537.36", "(KHTML,", "like", "Gecko)", "Chrome/35.0.1916.153", "Safari/537.36\"", "404", "123", "F", "21549", "50", "0", "-", "Test1"]

Expected:-

str =  ["2014-09-04 21:12:05", "5469687123030383463", "192.168.1.2", "4", "7879", "0", "43", "www.test.com/", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36", "404", "123", "F", "21549", "50", "0", "-", "Test1"] 

How can i achieve via ruby

Upvotes: 2

Views: 57

Answers (2)

tokland
tokland

Reputation: 67900

Your string looks so similar to UNIX shell arguments that I'd just use Shellwords::shellsplit. Note that this removes the quotes, but do you really need them?

require 'shellwords'
Shellwords::shellsplit(str)
#=> ["2014-09-04 21:12:05", "5469687123030383463", ..., "-", "Test1"]

Upvotes: 2

Patrick Oscity
Patrick Oscity

Reputation: 54734

You can cover both cases separately in your regex and join them with |:

str.scan(/"[^"]+"|[^ ]+/)

Upvotes: 2

Related Questions