Forum: Ruby Matching arbitrary number of fields

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C06405cc37a9abceff09e36fa8cf9e51?d=identicon&s=25 Adam Bender (Guest)
on 2009-05-06 07:24
(Received via mailing list)
I want to parse commands from a text file.  The commands are of the
form:
command "param 1" "param 2"
command "param"
command "param 1" "param 2" "param 3"
Each command will have one or more parameters.  Each parameter is
enclosed
in "" marks, and may be one or more words.  Is there a regular
expression
that will match each command without knowing ahead of time how many
parameters there are?
I tried something like this:
line =~ /^(\S+)(?:\s+\"([^\"]*)")+$/
But that only matches the command and the last parameter; I believe $2
is
being overwritten as the match progresses.  Is there a way to do this
with a
single regular expression?

Thanks,

Adam
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2009-05-06 09:30
(Received via mailing list)
On Wed, May 6, 2009 at 7:23 AM, Adam Bender <abender@gmail.com> wrote:
> But that only matches the command and the last parameter; I believe $2 is
> being overwritten as the match progresses.  Is there a way to do this with a
> single regular expression?
I could not come up with one, but why would you need a single regular
expression?

command, params = line.split( /\s+/, 2 )
[ command ] + params.scan(/\s*"(.*?)"/).flatten

seems to work fine.
HTH
Robert



--
Si tu veux construire un bateau ...
Ne rassemble pas des hommes pour aller chercher du bois, préparer des
outils, répartir les tâches, alléger le travail… mais enseigne aux
gens la nostalgie de l’infini de la mer.

If you want to build a ship, don’t herd people together to collect
wood and don’t assign them tasks and work, but rather teach them to
long for the endless immensity of the sea.
This topic is locked and can not be replied to.