How can I parse quoted CSV in Perl with a regex?

前端 未结 7 1450
青春惊慌失措
青春惊慌失措 2020-11-30 09:10

I\'m having some issues with parsing CSV data with quotes. My main problem is with quotes within a field. In the following example lines 1 - 4 work correctly but 5,6 and 7 d

7条回答
  •  抹茶落季
    2020-11-30 09:51

    Tested:

    
    use Test::More tests => 2;
    
    use strict;
    
    sub splitCommaNotQuote {
        my ( $line ) = @_;
    
        my @fields = ();
    
        while ( $line =~ m/((\")([^\"]*)\"|[^,]*)(,|$)/g ) {
            if ( $2 ) {
                push( @fields, $3 );
            } else {
                push( @fields, $1 );
            }
            last if ( ! $4 );
        }
    
        return( @fields );
    }
    
    is_deeply(
        +[splitCommaNotQuote('S,"D" REL VALVE ASSY,000771881,')],
        +['S', '"D" REL VALVE ASSY', '000771881', ''],
        "Quote in value"
    );
    is_deeply(
        +[splitCommaNotQuote('S,"BELT V,FAN",000324244,')],
        +['S', 'BELT V,FAN', '000324244', ''],
        "Strip quotes from entire value"
    );
    

提交回复
热议问题