Perl: Split a string on a delimiter, but respect single and double quotes with the delimiter
It's a common practice to split a string on a delimiter like a comma or semi-colon. If your input data contains the delimiter in quotes you need to respect that and not split there. I wrote a simple function to handle 99% of the use cases for splitting in this manner.
quote_split(qq{foo, bar, baz}); # ('foo', 'bar', 'baz')
quote_split(qq{"That's, mine"}); # ("That's mine")
# Split a string on commas, but respect single and double quotes with commas
sub quote_split {
my ($str, $separator) = @_;
$separator //= ",";
if (!length($separator)) {
die("quote_split separator cannot be empty\n");
}
my $separator_re = quotemeta($separator);
my @items;
while ($str =~ /\G\s*(?:
"((?:\\.|[^"\\])*)" # Double-quoted
| '((?:\\.|[^'\\])*)' # Single-quoted
| ((?:(?!$separator_re)[\s\S])+) # Unquoted
)\s*(?:$separator_re|\z)/gcx) {
my $item = $1 // $2 // $3;
# Unescape quoted values
$item =~ s/\\(['"\\])/$1/g;
push(@items, $item);
}
return @items;
}
Tags:



