Matching arbitrary number of fields

A

Adam Bender

[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
 
R

Robert Dober

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top