[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Matching arbitrary number of fields

Adam Bender

5/6/2009 5:24:00 AM

[Note: parts of this message were removed to make it a legal post.]

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

1 Answer

Robert Dober

5/6/2009 7:29:00 AM

0

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