从字符串中提取特定字符串(正则表达式?)

时间:2012-07-14 17:27:57

标签: regex

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

所以一些例子“说明”

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 8FLY 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
}

1 个答案:

答案 0 :(得分:1)

你可以这样做。

//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')
    );

请注意,模式存储为REGEXP文字。另请注意,尽管原始代码中有注释,matches[0]将始终是整个匹配,因此这不能是第一个令牌(4)。这将在matches[1]

我在模式中假设令牌可以是任何字母数字(\w),不一定是数字。根据需要进行调整。

最后,为了允许不区分大小写,只需在每个模式(i)之后添加/pattern/i标记。

相关问题