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,293
  • 1
  • 10
  • 18

2 Answers2

0

How about the code using scan like this ?

str.scan(/((?:(?:\"[^"]*\")|[^,])*),?/)[0...-1].map(&:first)
Tsuneo Yoshioka
  • 7,504
  • 4
  • 36
  • 32
0

This is probably what you are looking for

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

From: Regex to split a CSV

Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
kvp2982
  • 151
  • 5