Generate a list of words and quoted strings (allowing quoted quotes). For example:

two words "and a \"quoted\" string" -> two words "and a \"quoted\" string"
my @fields = m/\s* ("(?:(?!(?<!\\)").)*" | '(?:(?!(?<!\\)').)*' | +\S+)/gx;

Replies are listed 'Best First'.
Re: Parse line into fields of words and quoted strings
by merlyn (Sage) on Jan 03, 2007 at 01:49 UTC

      Only that it took 1/2 an hour first asking in the CB if anyone knew of a module to do the job, then fussing with the regex to get the correct result! :(

      Now at least I guess there is something to Super search for.

      Update: and the handling of \ by quotewords is 'interesting'. Consider:

      use strict; use warnings; use Text::ParseWords; while (<DATA>) { chomp; my @fields = m/\s* ("(?:(?!(?<!\\)").)*" | '(?:(?!(?<!\\)').)*' | +\S+)/gx; my @words = quotewords('\\s+', 0, $_); print ">", join ('<, >', @fields), "<\n"; print ">", join ('<, >', @words), "<\n\n"; } __DATA__ two words "and a \"quoted\" string" two words 'and a \'quoted\' string'

      Prints:

      >two<, >words<, >"and a \"quoted\" string"< >two<, >words<, >and a "quoted" string< >two<, >words<, >'and a \'quoted\' string'< >two<, >words<, >and a \'quoted\' string<

      Stripping the outer quotes by quotewords however may be a bonus, or not.


      DWIM is Perl's answer to Gödel