in reply to In need of a stupid regex trick

It's easier to do this with m//g than split. @list = $string =~ /"[^"]+"|\S+/g @list = grep defined, $string =~ /"([^"]*)"|(\S+)/g; Update: don't leave quotes on; allow empty string ""

Doesn't handle backslashes before " specially; if there is an unmatched " in the input, you'll get one it returned as part of an element.

Replies are listed 'Best First'.
Re: Re: In need of a stupid regex trick
by Anonymous Monk on Jan 04, 2004 at 22:12 UTC
    perl -wle '@l = split(/(?:"([^"]*)"|\s+)/, $ARGV[0]);$,="\t";print @l;' 'one "two three" four "five"'
      Nice.

      Slight tweaks to require space around "quoted string" (which you may or may not want) and remove undef entries. Update: and remove empty entries.

      perl -wle'@list = grep defined && length, split /(?:(?<!\S)"([^"]*)"(? +!\S))|\s+/, shift;print for @list' 'one "two three" four "five"'
      perl -wle'@list = grep defined, split /(?:(?<!\S)"([^"]*)"(?!\S))|\s+/ +, shift;print for @list' 'one "two three" four "five"'
        I can't see how it would be able to get undef.. Do you happen to have an example which has undef entries?