Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

regex to split on ' ', but skip spaces inside quotes

by true_atlantis (Acolyte)
on Sep 21, 2007 at 20:52 UTC ( [id://640437]=perlquestion: print w/replies, xml ) Need Help??

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

is there a way to do a split regular expression which will split on space, unless the space is in between quotes? for example:

hi my name is 'john doe'

would parse to:
hi
my
name
is
'john doe'

thanks!
  • Comment on regex to split on ' ', but skip spaces inside quotes

Replies are listed 'Best First'.
Re: regex to split on ' ', but skip spaces inside quotes
by artist (Parson) on Sep 21, 2007 at 21:14 UTC
    use quotewords from Text::ParseWords
    use Text::ParseWords qw(quotewords); my $line = q(hi my name is 'john doe'); @words =quotewords(' ', 0, $line); print join "\n", @words,"\n";
    --Artist
Re: regex to split on ' ', but skip spaces inside quotes
by duff (Parson) on Sep 21, 2007 at 21:10 UTC

    Rather than thinking in terms of "splitting on spaces", may be it would work better if you thought in terms of "gather the things I want". For instance, would this work for you:

    #!/usr/bin/perl use strict; use warnings; my $string = q(hi my name is 'john doe'); my @parts = $string =~ /'.*?'|\S+/g; print map { "$_\n" } @parts; __END__
    ?
Re: regex to split on ' ', but skip spaces inside quotes (3WTDI)
by tye (Sage) on Sep 21, 2007 at 23:51 UTC
    my @words= $string =~ /'[^']*'|\S+/g; my @words= $string =~ /'(?:\\.|[^\\']+)*'|\S+/gs; my @words= $string =~ /'(?:''|[^']+)*'|\S+/g;

    - tye        

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-23 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found