By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,594 Members | 3,552 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,594 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.
Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
GIMME wrote:
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
Jul 19 '05 #2

P: n/a
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 <Jo*******@inwap.com> wrote in message news:<zhjWb.3517
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.