例如,我有这种格式的任意行:
目录C:\ Program Files \ abc \ def \
或类似的东西。
启用日志
我希望能够从第一行中提取“C:\ Program Files \ ab \ def \”部分。同样,我想在第二行中提取“On”。变量与其值之间的空格是任意的。我将知道变量的名称,但我需要根据它提取值。
所以基本上,我想删除第一个单词和第一个单词后面的一些任意空格,并返回剩下的直到行尾。
答案 0 :(得分:4)
假设“word”是指“一串没有空格的字符”,你可以这样做:
for line in ioFile:lines() do
local variable, value = line:match("(%S+)%s+(.+)")
... --Do stuff with variable and value
end
答案 1 :(得分:0)
Nicol Bolas展示了string.match
的另一种选择,这是另一种选择:
function splitOnFirstSpace(input)
local space = input:find(' ') or (#input + 1)
return input:sub(1, space-1), input:sub(space+1)
end
用法:
local command, param = splitOnFirstSpace(line)
如果没有给出参数(splitOnFirstSpace('no-param-here')
),则param
为空字符串。
答案 2 :(得分:-1)
我不相信Lua使用像Ruby或Perl这样的split()函数打包。
我发现这个人构建了一个lu版本的Perl的分割功能: http://lua-users.org/lists/lua-l/2011-02/msg01145.html
如果你可以保证参数前面只有一个单词,那个单词不包含任何空格,你可以读取该行,在其上运行split函数,并使用返回数组的1索引值作为你想要的。
您也可以进行错误检查,并确保在预期目录中获得“C:\”,或检查以确保字符串==“开启”或“关闭”。由于使用硬编码的索引值,我真的提倡您错误检查您的预期值。没有什么比假设值错了更糟糕。
如果检测到错误,请务必将其记录或打印到屏幕上,以便了解相关信息。
这可能会捕获可能输入的字符串不正确的错误。
一些简单的代码可以模拟我的建议:
line = "directory C:\Program Files\abc\def/";
contents = line.split(" "); --Split using a space
directory = contents[2]; --Here is your directory
if(errorCheckDir(directory))
--Use directory
end
编辑: 为了回应下面的评论,Lua确实开始索引为1而不是0。 此外,在目录包含空格(可能)而不是简单地使用内容[2]的情况下,我将遍历除索引1之外的所有内容,并将目录重新组合在一起,确保在每个目录之间添加所需的空间你附上的索引。
因此,在上面的情况中,内容[2]和内容[3]必须与之间的空格一起缝合,以恢复正确的目录。
directory = contents [2] ..“”.. contents [3]
使用一个包含循环的函数可以很容易地自动执行此操作并返回正确的目录:
function recoverDir(contents)
directory = "";
--Recover the directory
for i=2, table.getn(contents) do
directory = directory..contents[i].." ";
end
--strip extra space on the end
dirEnd = string.len(directory);
directory = string.sub(directory,1,dirEnd-1);
return directory; --proper directory
end