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
}
You could do something like this.
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 inmatches[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
iflag after each pattern (/pattern/i).