0

私は、ユーザーが物事を行うための「指示」を書くことができるように、プロジェクトの一種の指示文字列パーサーを書いています。

だからいくつかの例「指示」

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
}
4

1 に答える 1

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)。

于 2012-07-14T17:52:23.330 に答える