1

我想知道是否可以使用正则表达式或类似的方法从预定义的句子中提取一些变量。

例如

如果这是模式...

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

还有人打字...

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

我怎么能以某种方式返回...

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

我还想在检索变量之前返回它与模式匹配的事实,因为会有许多不同的模式。注意:某人也可以键入多个单词来代替 *,例如johnny english而不是johnny

谢谢

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

基于 Derek 的回答和 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 回答