1

I have these line of strings:

#input:
"A & B/C,1,2"
"\"D, E & F\",1,2"

which I would like to convert into arrays.

#output:
["A & B/C",1,2]
["D, E & F",1,2]

split(",") is not suitable for this, so I tried regex:

str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")
str.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)")

both of these produces extra quote on the output:

["A & B/C,1,2"]
["\"D, E & F\",1,2"]

Can you please point out the wrong in the regex?

Fernand
  • 1,185
  • 1
  • 9
  • 18

2 Answers2

0

How about the code using scan like this ?

str.scan(/((?:(?:\"[^"]*\")|[^,])*),?/)[0...-1].map(&:first)
Tsuneo Yoshioka
  • 6,884
  • 3
  • 33
  • 30
0

This is probably what you are looking for

(?:^|,)(?=[^"]|(")?)"?((?(1)[^"]*|[^,"]*))"?(?=,|$)

From: Regex to split a CSV

Rajagopalan
  • 4,496
  • 2
  • 7
  • 25
kvp2982
  • 131
  • 5