split on comma, UNLESS comma is within ""

Posted on 2006-04-17
Last Modified: 2007-12-19
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.
Question by:hank1
    LVL 5

    Expert Comment

    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";
    LVL 1

    Author Comment

    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.
    LVL 84

    Expert Comment

    perldoc -w split
    LVL 5

    Expert Comment

    >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.
    LVL 84

    Expert Comment

    #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
    LVL 5

    Expert Comment

    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.
    LVL 5

    Accepted Solution

    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.
    LVL 3

    Expert Comment

    # Split a comma delimited string, where commas may appear inside quotes:

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


    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (,  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
    There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now