Robert Dober
5/6/2009 7:29:00 AM
On Wed, May 6, 2009 at 7:23 AM, Adam Bender <abender@gmail.com> wrote:
> I want to parse commands from a text file. =A0The commands are of the for=
m:
> command "param 1" "param 2"
> command "param"
> command "param 1" "param 2" "param 3"
> Each command will have one or more parameters. =A0Each parameter is enclo=
sed
> in "" marks, and may be one or more words. =A0Is there a regular expressi=
on
> that will match each command without knowing ahead of time how many
> parameters there are?
> I tried something like this:
> line =3D~ /^(\S+)(?:\s+\"([^\"]*)")+$/
> But that only matches the command and the last parameter; I believe $2 is
> being overwritten as the match progresses. =A0Is there a way to do this w=
ith a
> single regular expression?
I could not come up with one, but why would you need a single regular
expression?
command, params =3D line.split( /\s+/, 2 )
[ command ] + params.scan(/\s*"(.*?)"/).flatten
seems to work fine.
HTH
Robert
--=20
Si tu veux construire un bateau ...
Ne rassemble pas des hommes pour aller chercher du bois, pr=E9parer des
outils, r=E9partir les t=E2ches, all=E9ger le travail=85 mais enseigne aux
gens la nostalgie de l=92infini de la mer.
If you want to build a ship, don=92t herd people together to collect
wood and don=92t assign them tasks and work, but rather teach them to
long for the endless immensity of the sea.
--
Antoine de Saint-Exup=E9ry