Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: How can I split a comma-delimited string when the fields can have commas in them?

by turnstep (Parson)
on Mar 29, 2000 at 22:13 UTC ( #6441=note: print w/replies, xml ) Need Help??


in reply to How can I split a comma-delimited string when the fields can have commas in them?

Here's an answer from Mastering Regular Expressions:

sub parse_csv { my $text = shift; ## record containing comma-separated values my @new = (); push(@new, $+) while $text =~ m{ ## the first part groups the phrase inside the quotes "([^\"\\]*(?:\\.[^\"\\]*)*)",? | ([^,]+),? | , }gx; push(@new, undef) if substr($text, -1,1) eq ','; return @new; ## list of values that were comma-spearated } ## Use like this: @goodlist = parse_csv($csvlist);

Ugly, to be sure, but the complexity level really kicks up a notch when you add the delimiters into the fields themselves. Also, the above snippet allows quotes inside the fields, as long as they are backslashed.

  • Comment on Re: How can I split a comma-delimited string when the fields can have commas in them?
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://6441]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2023-03-29 07:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (70 votes). Check out past polls.

    Notices?