Perl expression for parsing CSV (ignoring parsing commas when in double quotes)

G

GIMME

I can't figure an expression needed to parse a string.

This problem arrises from parsing Excel csv files ...

The expression must parse a string based upon comma delimiters,
but if a comma appears in double quotes it should not be used for parsing.

For example in the simple case we'd have :

$a='hello,brave,world';

($v,$x,$y) = split(/,/,$a);

Should yeild (no suprise here)

hello for $v
brave for $x, and
world for $y


For the more advanced case we'd have :

$a='hello,"brave, but cruel, and joyous","planet, or world"';

hello for $v
brave, but cruel, and joyous for $x, and
planet, or world for $y


Thanks in advance to the kind souls who are sharp enough to get this one.
 
J

Joe Smith

GIMME said:
I can't figure an expression needed to parse a string.
Thanks in advance to the kind souls who are sharp enough to get this one.

#!/bin/perl
use Text::CSV;
my $a = 'hello,"brave, but cruel, and joyous","planet, or world"';
my $csv = Text::CSV->new();
my $status = $csv->parse($a);
my @fields = $csv->fields();
print "a=$a status=$status fields=\n\t", join("\n\t",@fields), "\n";

-Joe
 
G

GIMME

Thanks very much Joe.

I didn't say it but I found a post which easily translated
to Java and ORO ... Next time I'll look before posting.
Haha haha.

This

while($_){
s/([^,]*?(".*?")*)(,|$)//;
push @out, $1;
}

Became this ...

import org.apache.oro.text.perl.Perl5Util;

public String[] parseRecordString(String record) {
ArrayList r = new ArrayList();
while(! record.equals("") ) {
record = P5UTIL.substitute("s/([^,]*?(\".*?\")*)(,|$)//",record);
r.add(P5UTIL.group(1));
}
return (String[]) r.toArray(new String[r.size()]);
}


Joe Smith <[email protected]> wrote in message news:<zhjWb.3517
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top