Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hi all,
I have a pattern that I am trying to split properly, but I am having problems. Example:
"Foo,Bar","","Blah"
I need to extract anything in between the double quites, i.e:
Foo,Bar

Blah

@array = split(/"(.*)",/ , $line)

Replies are listed 'Best First'.
Re: split question
by FunkyMonk (Bishop) on May 29, 2008 at 22:20 UTC
      Though I think too that Text::CSV is the best to use here (especially since it can handle escaped quotes (\"), I think in this simple case, split *can* be used:
      (1) remove the very first and the very last quote, then:
      (2) split /","/,....
      -- 
      Ronald Fischer <ynnor@mm.st>
Re: split question
by toolic (Bishop) on May 29, 2008 at 23:20 UTC
    Yet another way, using a core module...
    use strict; use warnings; use Text::ParseWords; my @words = quotewords(',', 0, q{"Foo,Bar","","Blah"}); print "$_\n" for @words;
Re: split question
by PerlRob (Sexton) on May 29, 2008 at 22:37 UTC
    This will do what you want:
    my $string = '"Foo, Bar", "", "Blah"'; my @elements = $string =~ /"(.*?)"/g;
      Another way to do this would be to use a regex that avoids non-greedy matching by employing a negated character class, ie "([^"]*)" captures zero or more non-double quotes that are surrounded by double quotes.

      $ perl -le ' > $s = q{"Foo, Bar", "", "Blah"}; > @e = $s =~ m{"([^"]*)"}g; > print for @e;' Foo, Bar Blah $

      I hope this is of interest.

      Cheers,

      JohnGG

      thanks for both answers!