in reply to Regex - Matching prefixes of a word

This approach will only gets you deeper and deeper in more and more complicated regexes and levels within levels of if ... then ... else ... constructs. And if you add another command you have to start all over.

Better then to write a real and robust parser for your command language.

First you have to invent the grammar and syntax for your commands. Once you have that structure made, you can start thinking of writing the parser:

  1. Split the command into tokens
  2. Check each token for being a valid command or parameter (here the "partial" command regex can be used!)
  3. (re)assemble the tokens into a canonical format, which your backend engine can directly understand.

Higher Order Perl has some good examples how to do this.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: Regex - Matching prefixes of a word
by SuicideJunkie (Vicar) on Jul 28, 2009 at 14:42 UTC

    I do not actually have any nesting in the command structure. The code in the OP was just a simple way to test suggestions.

    The code actually used in the game is very easy to chain together:

    # Fire! $cmd =~ /^$regexSubstringOf{fire}\s+$regexName$regexIndexes\s*$/i ? se +tCommand($player, 'fire',[] , $1, $2) : # Lock weapons on a target $cmd =~ /^$regexSubstringOf{lock}\s+$regexName$regexIndexes\s+(?:on\s+ +)?$regexName$regexLockParams?\s*$/i ? setCommand($player, 'aim',[$4,$ +5,$3] , $1, $2) : ...
    Adding new ways to say a command is as easy as copy-pasting one of those lines. Adding new commands is slightly more complicated, as it requires adding backend code to the addCommand() function too.

    I had briefly considered a parser at first. I have already got one from another project that can evaluate math formulas, save variables and even do a form of looping. It didn't seem like a good idea at the time, because the token overlap (lock on dock, dock with lock) seemed like trouble, I expected I'd have to put at least as much effort into deciding based on tokens as on the regex captures, and finally, the direct regex way seemed pretty simple and straightforward.