K2xL
K2xL

Reputation: 10270

Extracting specific string from string (regexp?)

I am writing a sort of instruction string parser for a project so that users can write "instructions" to do things.

So some example "Instructions"

ADD 5 TO 3
FLY TO MOON
GOTO 10 AND MOVE 50 PIXELS

I assign these to an array of strings

var Instructions = ["ADD * TO *","FLY TO *", "GOTO * AND MOVE * PIXELS"];

If I have some:

var input = // String

And that string could be something like ADD 5 to 8 or FLY TO EARTH

Is there a regexp search of match I could use to help me find which instruction matched? For example

var numInstructions = Instructions.length;
for (var j = 0; j < numInstructions; j++)
{
     var checkingInstruction = Instructions[j];
     // Some check here with regexp to check if there is a match between checkingInstruction and input
     // Something like... 
     var matches = input.match(checkingInstruction);
     // ideally matches[0] would be the value at the first *, matches[1] would be the value of second *, and checkingInstruction is the instruction that passed
}

Upvotes: 0

Views: 85

Answers (1)

Mitya
Mitya

Reputation: 34556

You could do something like this.

//setup
var instruction_patterns = [/ADD (\w+) TO (\w+)/, /FLY TO (\w+)/],
    input = "ADD 4 TO 3",
    matches;

//see if any instructions match and capture details
for (var i=0, len=instruction_patterns.length; i<len; i++)
    if (matches = input.match(instruction_patterns[i]))
        break;

//report back
if (matches)
    alert(
        '- instruction:\n'+matches[0]+'\n\n'+
        '- tokens:\n'+matches.slice(1).join('\n')
    );

Note the patterns are stored as REGEXP literals. Also note that, despite the comment in your original code, matches[0] will always be the entire match, so this cannot be the first token (4). That will be in matches[1].

I have assumed in the patterns that the tokens could be anything alphanumeric (\w), not necessarily numbers. Adjust this as required.

Finally, to allow case-insensitive, just add the i flag after each pattern (/pattern/i).

Upvotes: 1

Related Questions