1

代码

if(x.substr(0,4)=='init') {
    output += 'Initialised<br>';        
    var rgx = /^\[typ-$\]/i;
    if (rgx.test(x))output+='Type given<br>';
    else output+='No type: '+x+'<br>';

}
container.append(output);

我正在尝试做的事情

我正在模拟网站的命令行终端。一个命令是init带有参数的type。通过键入以下内容设置参数:

 init [typ-Foo]

我试图然后获取type参数的值(在本例中为Foo)。

发生了什么

我根本无法获得价值。No Type: init [typ-Foo]当没有找到值时,它返回的是函数返回的内容。我以前没有玩过 Regex,所以我确定我的命令不正确,但我无法让它工作!

4

3 回答 3

3
var result = /\[typ-([^\]]+)]/.exec(  userInput  );
if (result){
 console.log("type: " + result[1]);
}
else {
 // no type
}

如果resultnull,则没有类型。如果不是,则类型在result[1]

这个正则表达式看起来有点复杂,因为我们在其特殊的正则表达式含义中使用[and ]s 并且也用作文字字符。

于 2013-08-22T13:18:29.510 回答
0

这种模式应该可以解决问题。

var rgx = /^init\s\[typ\-([^\]]+)\]/;

这就是发生的事情。

图片

来自Regexper.com

于 2013-08-22T13:21:43.423 回答
0

尝试更多类似的东西:

var rgx = /^init \[typ-(.*)\]$/i;

m = x.match(rgx);

if ( m != null ) {
    output += 'Initialised<br>';
    output+='Type given<br>';
    output+='Argument: ' + m[1]; // note this is the "Foo" value
}
else {
    output+='No type: '+x+'<br>';
}
container.append(output);
于 2013-08-22T13:21:44.817 回答