Lua读取字符串开头

26

我正在制作一个冒险游戏,我试图让用户输入一个字符串,如果字符串以 "action" 开头,则在一个函数中读取该行的其余部分。

act=io.read();
if act=="blah" then doSomething();
elseif act=="action"+random string then readRestOfStringAndDoSomethinWwithIt();
else io.write("Unknown action\n");
end
3个回答

41

看一下这个页面: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 ...

19

使用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 方法只应在没有这样的锚点时添加 ^ 锚定符。

1
这里只是一个注释:如果你使用像self:find('^' .. str)或sub/gsub、match等这样的函数,你必须手动转义正则表达式字符,否则如果你有特殊字符如/*.+等,它们将无法正常工作。 - Corneliu Maftuleac
1
使用find的问题在于你需要在str中转义正则表达式特殊字符。 - eadmaster

5
也许有很多不同的方法来解决这个问题,以下是其中一个。
userInput = ... -- however you're getting your cleaned and safe string
firstWord = userInput:match("^(%S+)")
-- validate firstWord

你可能需要编写自己的语句解析器,将字符串处理为已知的标记等。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接