我已经用谷歌搜索过,但是还是不明白。这似乎是一个很简单的函数,但当然 Lua 并没有它。
在 Python 中,我会这样做:
string = "cat,dog"
one, two = string.split(",")
那我会有两个变量,一个是等于猫的one,另一个是等于狗的two。
在Lua中怎么做呢?
试一下这个
str = 'cat,dog'
for word in string.gmatch(str, '([^,]+)') do
print(word)
end
'[^,]'代表“除了逗号以外的所有字符”,加号意味着“一个或多个字符”。括号创建一个捕获组(在这种情况下并不是非常需要)。
string = "cat,dog"
one, two = string:match("([^,]+),([^,]+)")
在您的页面顶部添加此拆分功能:
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
然后按如下操作:
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
了解更多信息,请访问:教程:Lua字符串魔法
继续编码...............:)
function split(source, delimiters)
local elements = {}
local pattern = '([^'..delimiters..']+)'
string.gsub(source, pattern, function(value) elements[#elements + 1] = value; end);
return elements
end
-- 例子:var elements = split("bye# bye, miss$ american@ pie", ",#$@ ") -- 返回 "bye" "bye" "miss" "american" "pie"
该函数的作用是将字符串按照指定的分隔符进行分割,返回一个由分割后的子串组成的数组。
也可以处理可选的空格:
str = "cat,dog,mouse, horse"
for word in str:gmatch('[^,%s]+') do
print(word)
end
cat
dog
mouse
horse
str = "cat,dog"
local result = mw.text.split(str,"%s*,%s*")
-- result[0] will give "cat", result[1] will give "dog"
实际上,如果您不关心空格,可以使用以下方法:
str = "cat,dog"
local result = mw.text.split(str,",")
-- result[0] will give "cat", result[1] will give "dog"
string.split()
这样的函数在Lua中大多是不必要的,因为你可以用LPEG表达字符串操作。如果你仍需要一个专用函数,方便的方法是定义一个分隔符工厂(下面片段中的mk_splitter()
),然后从中派生自定义分隔符。
local lpeg = require "lpeg"
local lpegmatch = lpeg.match
local P, C = lpeg.P, lpeg.C
local mk_splitter = function (pat)
if not pat then
return
end
pat = P (pat)
local nopat = 1 - pat
local splitter = (pat + C (nopat^1))^0
return function (str)
return lpegmatch (splitter, str)
end
end
,
字符处分割的函数:commasplitter = mk_splitter ","
print (commasplitter [[foo, bar, baz, xyzzy,]])
print (commasplitter [[a,b,c,d,e,f,g,h]])