re = /"(?:[^"]|"")*"|[^,\n]+|(?=,)(?<=,)|^|(?<=,)$/m
str = 'record 1:field 1,record 1:field 2,record 1:field 3
record 2:field 1,record 2:field 2,record 2:field 3
"quoted field","quoted field, with comma", "whitespace before & affer quote" ,"new
line in field","double quotes ""in"" field","double quotes in field "","" with comma"
,,,<- empty fields at beging, , ,<-whitespace fields,empty fields at end ->,,
^empty records'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html