# Matching arbitrary number of fields

**URL:** <https://www.ruby-forum.com/t/matching-arbitrary-number-of-fields/167264>\
**Category:** Ruby\
**Created:** [May 6, 2009, 7:24am UTC](https://www.ruby-forum.com/t/matching-arbitrary-number-of-fields/167264 "2009-05-06T07:24:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![adambeazley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@adambeazley](https://www.ruby-forum.com/u/adambeazley)\
**Post date:** [May 6, 2009, 7:24am UTC](https://www.ruby-forum.com/t/matching-arbitrary-number-of-fields/167264/1 "2009-05-06T07:24:16Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![adambeazley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@adambeazley](https://www.ruby-forum.com/u/adambeazley)\
**Post date:** [May 6, 2009, 9:30am UTC](https://www.ruby-forum.com/t/matching-arbitrary-number-of-fields/167264/2 "2009-05-06T09:30:42Z")

</div>

On Wed, May 6, 2009 at 7:23 AM, Adam B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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.
