• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3020
  • Last Modified:

split on comma, UNLESS comma is within ""

Excel outputs .csv file.

If the sheet cell contained a comma, the cell is quoted.

.csv output:
  cellone,celltwo,"cell has, comma",cell four

If the sheet cell containes a quote, it's repeated

excell cells:
  cell"one  celltwo

.csv output

How can you split on a 'comma'?  I can delete the double second quote later.
1 Solution
well if I understand correctly, you want to split on commas that are NOT in a quoted string?  This can be tricky since the split() function will not differentiate between the two.  You can push perl in the right direction though by doing some altering first:

my $string = 'cellone,celltwo,"cell has, comma",cell four';
$string =~ s/"(.*?)\,(.*?)"/$1::$2/g;
for (split(/\,/, $string)) {
   print $_,"\n";
hank1Author Commented:
I don't think I want to add characters to intermediate results.
They may also be there. :-)
The more I look at this, the more it appears its a little program.
perldoc -w split
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

>I don't think I want to add characters to intermediate results.
>They may also be there. :-)
>The more I look at this, the more it appears its a little program.

I am not sure you fully understand.  My example above adds nothing to any intermediate results.  It temporarily masks the commans inside of double quotes so split() does not split on them and then changes them back for further processing.
#this does not work
my $string = '"cellone",celltwo,cellthree,"cell, has, comma",cell::four';
$string =~ s/"(.*?)\,(.*?)"/$1::$2/g;
for (split(/\,/, $string)) {
   print $_,"\n";

perldoc -q split
       How can I split a [character] delimited string except when inside
       [character]? (Comma-separated files)

               Take the example case of trying to split a string that is
               comma-separated into its different fields.  (We'll pretend you
               said comma-separated, not comma-delimited, which is different
               and almost never what you mean.) You can't use "split(/,/)"
               because you shouldn't split if the comma is inside quotes.  For
               example, take a data line like this:

                   SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"

               Due to the restriction of the quotes, this is a fairly complex
               problem.  Thankfully, we have Jeffrey Friedl, author of a
               highly recommended book on regular expressions, to handle these
               for us.  He suggests (assuming your string is contained in

                    @new = ();
                    push(@new, $+) while $text =~ m{
                        "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the phrase inside the quotes
                      | ([^,]+),?
                      | ,
                    push(@new, undef) if substr($text,-1,1) eq ',';

               If you want to represent quotation marks inside a quotation-
               mark-delimited field, escape them with backslashes (eg, "like
               \"this\"".  Unescaping them is a task addressed earlier in this

               Alternatively, the Text::ParseWords module (part of the stan-
               dard Perl distribution) lets you say:

                   use Text::ParseWords;
                   @new = quotewords(",", 0, $text);

               There's also a Text::CSV (Comma-Separated Values) module on
yes but you can say that about anything.  LOL..

Use 27 semi colons or 17 percent signs or something you are sure will not be in the object string naturally. No one solution will suffice for all possible data strings.  Even the example for comma seperated files above can be broken by carefully crafted quotes.
Oh and that example you gave is somewhat old, using extended regular expressions is not recommedned in perl 5 and probably will not even be supported in perl 6 (or so I have heard).  So recommending a depricated solution is not the best idea.

I would say the modules mentioned will be your best bet but if you are unable to install modules (in Text::CSV's case) you may have issues.  Text::ParseWords would be your best bet due to being included in the standard distrobution.  However if you wanted someone to simply post a link to a module you could have found on your own, then I say you waisted your points.  You could have searched cpan for either one of these on your own so I assumed you wanted a quick and dirty example of how it could be done.
# Split a comma delimited string, where commas may appear inside quotes:

undef @field;
push(@field, defined($1) ? $1:$3) while


Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now