我用谷歌搜索,我只是没有得到它.看起来像这么简单的功能,但当然Lua没有它.
在Python中,我会这样做
string = "cat,dog"
one, two = string.split(",")
Run Code Online (Sandbox Code Playgroud)
然后我会有两个变量,一个=猫.两个=狗
我如何在Lua中做到这一点!?
mar*_*cus 53
试试这个
str = 'cat,dog'
for word in string.gmatch(str, '([^,]+)') do
print(word)
end
Run Code Online (Sandbox Code Playgroud)
'[^,]'表示"除了逗号之外的所有内容,+符号表示"一个或多个字符".括号创建一个捕获(在这种情况下不是真的需要).
cat*_*ell 27
如果您可以使用库,答案是(通常在Lua中)使用Penlight.
如果Penlight对你来说太重了,你只想用你的例子中的单个逗号分割一个字符串,你可以这样做:
string = "cat,dog"
one, two = string:match("([^,]+),([^,]+)")
Run Code Online (Sandbox Code Playgroud)
Kri*_*lim 14
在页面顶部添加此拆分功能:
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
local theStart = 1
local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
while theSplitStart do
table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
theStart = theSplitEnd + 1
theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
end
table.insert( outResults, string.sub( self, theStart ) )
return outResults
end
Run Code Online (Sandbox Code Playgroud)
然后执行以下操作:
local myString = "Flintstone, Fred, 101 Rockledge, Bedrock, 98775, 555-555-1212"
local myTable = myString:split(", ")
for i = 1, #myTable do
print( myTable[i] ) -- This will give your needed output
end
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请访问:教程:Lua String Magic
保持编码............... :)
-- 像 C strtok 一样,再分割一个分隔符(查找不包含任何分隔符的每个字符串)
function split(source, delimiters)
local elements = {}
local pattern = '([^'..delimiters..']+)'
string.gsub(source, pattern, function(value) elements[#elements + 1] = value; end);
return elements
end
Run Code Online (Sandbox Code Playgroud)
-- 示例: var elements = split("bye# bye, miss$ american@ pie", ",#$@ ") -- 返回 "bye" "bye" "miss" "american" "pie"