Adam has asked for the wisdom of the Perl Monks concerning the following question: (regular expressions)

my $string = "first-item \"second item\" third-item"; my @items = split /???/, $string; my $i = 0; print ++$i, ": $_\n" for @items; # Would print: # 1: first-item # 2: "second item" # 3: third-item

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I split on a string except when inside quotes?
by merlyn (Sage) on Aug 24, 2000 at 21:10 UTC
Re: How can I split on a string except when inside quotes?
by Anonymous Monk on Nov 28, 2001 at 19:40 UTC
    This doesn't handle all the subtle things (backslashes, single-quotes, etc) that Text::ParseWords does, but it works for the simple cases, and produces your expected output exactly (quotes intact): my @items = ($string =~ /(".*?"|\S+)/g);
Re: How can I split on a string except when inside quotes?
by Coruscate (Sexton) on Feb 15, 2003 at 10:46 UTC

    Late entry: how about something like this:

    my $string = 'first-item "second item" ' . 'third-item "fourth item"'; my %items; push @{$items{ $1 =~ /"/ ? 'quoted' : 'unquoted' }}, $1 while $string =~ /(".*?"|\S+)/g; print 'Quoted: ', join(', ', @{$items{'quoted'}}), "\n"; print 'Unquoted: ', join(', ', @{$items{'unquoted'}}), "\n";