Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Parse line into fields of words and quoted strings

by GrandFather (Saint)
on Jan 03, 2007 at 01:42 UTC ( [id://592682]=CUFP: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

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

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

    No recent polls found