2

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

3
  • So you need to split string on whitespaces? Commented Sep 8, 2014 at 9:24
  • Yes. But some values contains double quotes. Commented Sep 8, 2014 at 9:25
  • watch out split with whitespace result and expected result.It has differences Commented Sep 8, 2014 at 9:28

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

i got what i expected using shellwords. Thanks.
Great! Maybe you should change the expected output in the question then. Note also that the URL does not match.
2

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

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

1 Comment

Wow. This is beautiful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.