How could I split commas excepts it's in double quotes

s1 ='a,b,c,"x,y,z" '
m1 = s1.split(',') 

"x,y,z" should not be splitted by comma

The expected result should be [‘a’,’b’,’c’,”x,y,z”], total size is 4

How could I do that in Ruby

  • “uninitialized constant Cucumber::Rb_Support (NameError)” when running Cucumber for Ruby & Watir
  • Zero-length string being returned from String#split
  • Rails: How to get Jquery to update a database column after a click
  • Mechanize using ruby open up new page
  • uninitialized constant API::V1::MusicController
  • Rails: HasManyThroughAssociationNotFoundError
  • Add rb-grib gem to Rails application
  • Check a field is contains in another list in ROR
  • 3 Solutions collect form web for “How could I split commas excepts it's in double quotes”

    Use the csv module:

    irb(main):001:0> require 'csv'
    => true
    irb(main):002:0> CSV.parse_line('a,b,c,"x,y,z"')
    => ["a", "b", "c", "x,y,z"]
    

    Try this:

    s1 ='a,b,c,"x,y,z" '
    
    quotes = s1.match(/".+"/)
    
    s1.split(/,(?![#{quotes}])|,(?=")/)
    

    Could it be? Is it possible? Do I finally have a chance to use Ruby’s bordering-on-bizarre flip-flop operator?

    Let’s try:

    str ='a,b,c,"x,y,z",d,e,"1,2,3",f '
    
    u = ''  
    str.split(?,).each_with_object([]) do |s,a|
      t = s.strip
      if (t[0]==?") .. (t[-1]==?")
        u = '' if t[0]==?"
        u << t
        if t[-1]==?"
          a << u
        else
          u << ?,
        end
      else
        a << t
      end
    end
      #=> ["a", "b", "c", "\"x,y,z\"", "d", "e", "\"1,2,3\"", "f"] 
    
    Ruby is the best programming language in the world - Ruby on Rails.