1

How can I split by fields below (this is sql format)? Previously I use to just split by ', ' the problem it fails if that character sequence is within the quotes. Unfortunately I also can't split by quotes because the numbers don't have any.

mystring = "(1, 'data, ', 'data_two, ', 'Test 34', '', 'gb', 1, '1')"
mystring.split(', ')

I need to get

'1'
'data'
'data_two, '
'Test 34'
''
'gb'
'1'
'1'
5
  • My bad fixed forgot the quotes Commented Nov 9, 2012 at 21:32
  • check out the answer below... please approve if this works for you Commented Nov 9, 2012 at 21:39
  • 4
    Why don't you use CSV, since it is designed to handle strings like that? Commented Nov 9, 2012 at 21:40
  • 1
    Also, if you're trying to split apart a SQL response, use an ORM like Sequel, to talk to the DBM. It'll make your life easier. Commented Nov 9, 2012 at 21:52
  • Why do you want to strip the comma on the second item but not the third? Commented Nov 9, 2012 at 22:22

3 Answers 3

1

If you strip the parens, you can coerce it into being parseable using CSV with options.

CSV.parse_line(mystring[1..-2], {:col_sep=>", ", :quote_char=>"'"})

 => ["1", "data, ", "data_two, ", "Test 34", "", "gb", "1", "1"]
Sign up to request clarification or add additional context in comments.

Comments

0
mystring.split(/,/).map{|x| x.gsub(/[()\']/,'').strip}
 => ["1", "data", "", "data_two", "", "Test 34", "", "gb", "1", "1"] 

1 Comment

Because there could be a comma in between quotes like there is in the second item
0

This may be helpful:

irb(main):001:0> mystring
=> "(1, 'data, ', 'data_two, ', 'Test 34', '', 'gb', 1, '1')"
irb(main):002:0> mystring.scan(/(?:'(?:\\.|[^'])*'|[^,' ])+/)
=> ["(1", "'data, '", "'data_two, '", "'Test 34'", "''", "'gb'", "1", "'1')"]

Or, if you need quotes and braces to be removed, then:

irb(main):003:0> mystring.scan(/([^', ()]+)|'([^']*)'/).flatten.compact
=> ["1", "data, ", "data_two, ", "Test 34", "", "gb", "1", "1"]

This will match any non quote/brace/comma/space characted word, or anything inside of single 'quotes'. (Note, that escape sequence (\x) is not accounted in second example unlike first one. But it may be that you don't need such complications.)

Comments

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.