1

正規表現などを使用して、定義済みの文から多くの変数を抽出できるかどうか疑問に思っています。

例えば

このパターンだったら…

"How many * awards did * win in *?"

そして誰かがタイプした...

"How many gold awards did johnny win in 2008?"

どうにかして戻れるように...

["gold","johnny","2008"]

また、さまざまなパターンが存在するため、変数を取得する前にパターンに一致するという事実を返したいと思います。注: * の代わりに複数の単語を入力することもできます。例: johnnyだけでなくjohnny english

ありがとう

4

2 に答える 2

3
var text = "How many gold awards did johnny win in 2008?";
var query = text.match(/^How many ([^\s]+) awards did ([^\s]+) win in ([^\s]+)\?$/i);
query.splice(0,1); //remove the first item since you will not need it
query[0] //gold
query[1] //johny
query[2] //2008

詳細については、MDN - 一致を参照してください。

アップデート

に合わせたいようですjohny englishHow many gold awards did johnny english win in 2008?
これは、正規表現の更新版です。

/^How many (.+) awards did (.+) win in (.+)\?$/i
于 2012-06-27T18:45:46.093 に答える
1

デレクの答えとSimpleCoderのコメントに基づいて構築すると、ここに完全な機能があります:

// This function escapes a regex string
// http://simonwillison.net/2006/jan/20/escape/
function escapeRegex(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function match(pattern, text) {
    var regex = '^' + escapeRegex(pattern).replace(/\\\*/g, '(.+)') + '$';
    var query = text.match(new RegExp(regex, 'i'));
    if (!query)
        return false;

    query.shift(); // remove first element
    return query;
}

match("How many * awards did * win in *?", "How many gold awards did johnny win in 2008?");
于 2012-06-27T19:26:16.483 に答える