Split a string into a comma array if the comma is not inside quotation marks

Given an array string in Ruby with some elements in quotation marks that contain commas:

my_string.inspect # => "\"hey, you\", 21" 

How can I get an array:

 ["hey, you", " 21"] 
+5
source share
2 answers

The standard Ruby CSV library .parse_csv does just that.

 require 'csv' "\"hey, you\", 21".parse_csv # => ["hey, you", " 21"] 
+5
source

Yes, using CSV :: parse_line is the way to go here, but you can also do it with a regex:

 r = / (?: # Begin non-capture group (?<=\") # Match a double-quote in a positive lookbehined .+? # Match one or more characters lazily (?=\") # Match a double quote in a positive lookahead. ) # End non-capture group | # Or \s\d+ # Match a whitespace character followed by one or more digits /x # Extended mode str = "\"hey, you\", 21" str.scan(r) #=> ["hey, you", " 21"] 

If you prefer to have "21" rather than " 21" , just delete \s .

+1
source

Source: https://habr.com/ru/post/1234635/


All Articles