我正在为一个项目编写一种指令字符串解析器,以便用户可以编写“指令”来做事。
所以一些例子“说明”
ADD 5 TO 3
FLY TO MOON
GOTO 10 AND MOVE 50 PIXELS
我将这些分配给字符串数组
var Instructions = ["ADD * TO *","FLY TO *", "GOTO * AND MOVE * PIXELS"];
如果我有一些:
var input = // String
该字符串可能类似于ADD 5 to 8
或FLY TO EARTH
是否有一个匹配的正则表达式搜索可以用来帮助我找到匹配的指令?例如
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
}