我正在尝试为文本冒险游戏编写命令行解析器。我将命令写入数组:Look,Talk,Get等......
如何编写在命令行开头查找这些命令的正则表达式,忽略单词“at,with,on等...”然后在命令行中选取其余单词作为一个字符串。例如,如果用户键入: “与孤独的树谈话”,我希望正则表达式找到“谈话”作为命令,忽略“与”,然后将“孤独的树”变成一个字符串。任何代码建议吗?
这就是我想出来的,当我把它放到HTML中时页面是空白的:
//Iterate through the array to see if a command was used
var myStringArray = ["Look","Talk","Take"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
//When it picks a particular word up it will save it.
var str = "Talk with Lonely Tree";
var textcmd = +str.split(' ')[0];
//replace the command word and unnecessary other words in the text
if (i == textcmd){
var objecttxt = str;
objecttxt = str.replace(textcmd, "")
var myUselessWords = ["on","with","at","to"];
var uselessLength = myUselessWords.length;
for (var t = 0; t < uselessLength; t++) {
var uselessCollection = [];
uselessCollection.push = t;
objecttxt = str.replace(t, "");
}
}
alert(objecttxt + " " + textcmd);
}
答案 0 :(得分:0)
对于你的例子,这样的事情应该有效:
/(\blook|look|talk|get)\b.*\b(lonely\Wtree|something\Welse)\b/g
这会捕获您指定的任何“孤独树”对象的任何命令。如果您想使用RegExes,请尝试http://regexr.com/
在你的情况下,如果你有很多游戏命令和对象,我想你的正则表达式会变得非常大。如果首先检查命令,然后在第二步检查可能的对象,那么性能会更好。
答案 1 :(得分:0)
我会尝试不同的方法:
var input = userinput; //however you get it
var commands = [/look/i, /take/i, /talk/i];
var gameObjects = []; //push objects here as they're created
var command = commands.filter(function(r) { return input.match(r); });
var object = gameObjects.filter(function(obj) {
return input.match(new RegExp(obj.name, 'i');
});
if (command.length and object.length) {
//do stuff, remember that String.prototype.match returns an array even
//if there's only one match, so be sure to unbox
}