从字符串中提取特定字符串(regexp?)

从字符串中提取特定字符串(regexp?),regex,Regex,我正在为一个项目编写一种指令字符串解析器,这样用户就可以编写“指令”来做事情 因此,一些示例“说明” 我将它们分配给一个字符串数组 var Instructions = ["ADD * TO *","FLY TO *", "GOTO * AND MOVE * PIXELS"]; 如果我有: var input = // String 这个字符串可能类似于将5添加到8或飞到地球 是否有一个匹配的regexp搜索可以帮助我找到匹配的指令?比如说 var numInstructions = Ins

我正在为一个项目编写一种指令字符串解析器,这样用户就可以编写“指令”来做事情

因此,一些示例“说明”

我将它们分配给一个字符串数组

var Instructions = ["ADD * TO *","FLY TO *", "GOTO * AND MOVE * PIXELS"];
如果我有:

var input = // String
这个字符串可能类似于
将5添加到8
飞到地球

是否有一个匹配的regexp搜索可以帮助我找到匹配的指令?比如说

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
}
var numInstructions=Instructions.length;
对于(var j=0;j
您可以这样做

//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')
    );
//设置
var指令\u模式=[/ADD(\w+)TO(\w+/,/FLY TO(\w+/),
输入=“将4添加到3”,
比赛;
//查看是否有任何指令匹配并捕获详细信息

对于(var i=0,len=instruction_patterns.length;iYou需要给出所有可能的命令和运算符,然后才能给出“regex”这实际上会变成一个解析器。@ShoMinamimoto我希望有一些通配符可以代替X和Ys。那么你需要定义语法和可能的输入。X和Y是整数吗?字符吗?带空格的单词吗?命令可以有整数、符号等吗?(比如有一个叫做MOVE52的命令)。定义您想要捕获的内容和不想要的内容。@ShoMinamimoto理想情况下只捕获字符串(如果这样更容易,则不使用空格)
//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')
    );