我正在制作一个冒险游戏,我试图让用户输入一个字符串,如果字符串以 "action" 开头,则在一个函数中读取该行的其余部分。
act=io.read();
if act=="blah" then doSomething();
elseif act=="action"+random string then readRestOfStringAndDoSomethinWwithIt();
else io.write("Unknown action\n");
end
看一下这个页面:http://lua-users.org/wiki/StringRecipes
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
然后使用
elseif string.starts(act, "action") then ...
使用string.find
与^
配合,将模式锚定在字符串开头:
ss1 = "hello"
ss2 = "does not start with hello"
ss3 = "does not even contain hello"
pattern = "^hello"
print(ss1:find(pattern ) ~= nil) -- true: correct
print(ss2:find(pattern ) ~= nil) -- false: correct
print(ss3:find(pattern ) ~= nil) -- false: correct
你甚至可以将其作为所有字符串的方法:
你甚至可以将其作为所有字符串的方法:
string.startswith = function(self, str)
return self:find('^' .. str) ~= nil
end
print(ss1:startswith('hello')) -- true: correct
请注意,"some string literal":startswith(str)
不起作用:字符串文字没有像"方法"一样的string
表函数。您必须使用tostring
或函数而不是方法:
print(tostring('goodbye hello'):startswith('hello')) -- false: correct
print(tostring('hello goodbye'):startswith('hello')) -- true: correct
print(string.startswith('hello goodbye', 'hello')) -- true: correct
问题在于最后一行的语法有点令人困惑:第一个字符串是模式还是第二个字符串是模式?而且,模式参数(例如示例中的“hello”)可以是任何有效的模式;如果它已经以 ^ 开头,则结果是错误的负面,因此为了健壮起见, startswith 方法只应在没有这样的锚点时添加 ^ 锚定符。
userInput = ... -- however you're getting your cleaned and safe string
firstWord = userInput:match("^(%S+)")
-- validate firstWord
str
中转义正则表达式特殊字符。 - eadmaster