Hi,
I a comma separated string that contains “comma separated substrings”
like this:
str= ’ “hello ,there” ,how,are ,you, “I am , fine” ’
every substring that contains comma is in a " ".
I am trying to split str based on, so I should get something like:
“hello ,there”
how
are
you
“I am , fine”
tried many things like “split”, … didn’t work.
any idea how to do this.
Thank you
Paulo H. wrote in post #1141891:
Hi,
I a comma separated string that contains “comma separated substrings”
like this:
str= ’ “hello ,there” ,how,are ,you, “I am , fine” ’
every substring that contains comma is in a " ".
Here a first solution with split/gsub/map :
str= ’ “hello ,there” ,how,are ,you, “I am , fine” ’
i,h=0,{}
res=str.strip.gsub(/".?"/) { |m|
i+=1
mark=“ABC123-#{i}-321CBA”
h[mark]=m
mark
}.split(/\s,\s*/).map { |e|
h.each {|k,v| e.gsub!(k,v)} ; e
}
puts res.join("|")
“hello ,there”|how|are|you|“I am , fine”
Paulo H. wrote in post #1141891:
Hi,
And this one with StringScanner :
require ‘strscan’
str= ’ “hello ,there” ,how,are ,you, “I am , fine” ’
scanner= StringScanner.new(str.strip)
out=[]
loop {
w=scanner.scan(/.?("|,)/)
break unless w
out << w[0…-2].strip
if w[-1]==’"’
out << scanner.scan(/.?(?=")/)
scanner.scan(/.\s*/)
end
break if scanner.empty?
}
puts out.join("|")
|hello ,there||how|are|you||I am , fine
your csv isa bit malformed right?
require “csv”
CSV.parse_line(’“hello ,there”,how,are,you,“I am , fine”’)
#=> [“hello ,there”, “how”, “are”, “you”, “I am , fine”]