Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

How can I split on a string except when inside quotes?

by Adam (Vicar)
on Aug 24, 2000 at 21:09 UTC ( [id://29461]=perlquestion: print w/replies, xml ) Need Help??

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";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://29461]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-20 02:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found