Lua需要在逗号处分割。

40

我已经用谷歌搜索过,但是还是不明白。这似乎是一个很简单的函数,但当然 Lua 并没有它。

在 Python 中,我会这样做:

string = "cat,dog"
one, two = string.split(",")

那我会有两个变量,一个是等于猫的one,另一个是等于狗的two。

在Lua中怎么做呢?


1
可能是Split string in lua?的重复问题。 - hjpotter92
7个回答

71

试一下这个

str = 'cat,dog'
for word in string.gmatch(str, '([^,]+)') do
    print(word)
end

'[^,]'代表“除了逗号以外的所有字符”,加号意味着“一个或多个字符”。括号创建一个捕获组(在这种情况下并不是非常需要)。


37
如果您可以使用库,那么答案(在Lua中通常如此)是使用Penlight
如果Penlight对您来说太重了,而您只想像示例中一样使用单个逗号拆分字符串,您可以这样做:
string = "cat,dog"
one, two = string:match("([^,]+),([^,]+)")

16

在您的页面顶部添加此拆分功能:

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字符串魔法

继续编码...............:)


5
--类似于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

-- 例子:var elements = split("bye# bye, miss$ american@ pie", ",#$@ ") -- 返回 "bye" "bye" "miss" "american" "pie"

该函数的作用是将字符串按照指定的分隔符进行分割,返回一个由分割后的子串组成的数组。


4
为了处理可选的空格,您可以这样做:

也可以处理可选的空格:

str = "cat,dog,mouse, horse"
for word in str:gmatch('[^,%s]+') do
    print(word)
end

输出结果将为:
cat
dog
mouse
horse

2
这是我在Mediawiki上的做法:
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"

这里使用的API是在MediaWiki扩展Scribunto中实现的。这是split()方法参考文档和源代码。它依赖于Scribunto的Lua常用库中的许多其他功能,因此只有当您实际使用MediaWiki或计划导入大部分Scribunto常用库时,它才能为您工作。

1

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

使用LPEG的优点在于该函数接受有效的Lua字符串和模式作为参数。
以下是如何使用它创建一个将字符串在,字符处分割的函数:
commasplitter = mk_splitter ","

print (commasplitter [[foo, bar, baz, xyzzy,]])
print (commasplitter [[a,b,c,d,e,f,g,h]])

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