Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi,

 

Can anyone convert this Perl code to VB.NET?

 


sub parseCSV { # (str) returns array of CSV entries (commas separated fields)
   # start with Jeffrey E. F. Friedl, "Mastering Regular Expressions" method 
on p 205
   # modified to interpret "" as a quoted "
   # Correctly parses CSV file produced by Microsoft Excel 97.
   my $comma='';
   my $str = $_[0];
   my $preStr=$str;
   my @fields = (); # initialize to null
   until ( $str eq '' ) {
       my $thisField='';
       if( $str =~ m{^"([^",]*)"(|,(.*))$} ) {
           $thisField = $1;  $str=$3; $comma=$2;
       } elsif ( $str =~ m{^([^",]*)(|,(.*))$} ) {
           $thisField = $1;  $str=$3; $comma=$2;
       } elsif ( $str =~ m{^"(.*)$} ) { # there is a leading "
           $str=$1;
           # get all "" in remainder of this field
           while( $str =~ m{^([^"]*")"(.*)$} ) {
           	$thisField .= $1;
	$str=$2;
           };
           #hopefully we are at a [^,"]*", or " at end of line
           if( $str =~ m{([^"]*)"(|,(.*))$} ) {
           	$thisField .= $1;
               $str=$3;
               $comma=$2;
           } else {
           	warn "Could not find a \" following >$thisField< 
in\n>$preStr<";
               $thisField .= $str;
               $str='';
           };
       } else {
           warn "Could not match >$str< in\n>$preStr<";
           $str = '';
       };
       push( @fields, $thisField ); # add the just matched field
   }
   push( @fields, undef) if $comma =~ m/,$/; #account for an empty last field
   return @fields;
} # end parseCSV

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...