Lua拆分没有分隔符的字符串

时间:2013-10-25 14:48:47

标签: string lua split

有没有一种简单的方法来分割这样的字符串:

M34a79 or M2ab943 or M4c4

M,34,a,79 or M,2,ab,943 or M,4,c,4

没有任何分隔符?

3 个答案:

答案 0 :(得分:4)

您可以使用一对gsub调用来执行此操作:

x = "M34a79 or M2ab943 or M4c4"

x, _ = x:gsub( "(%d)(%a)", "%1,%2" )
x, _ = x:gsub( "(%a)(%d)", "%1,%2" )

print( x )
  

M,34,a,79或M,2,ab,943或M,4,c,4

可能并非在所有情况下都有效,但确实适用于您的示例。

答案 1 :(得分:0)

如果您不介意使用LPEG 库:

local lpeg            = require "lpeg"
local C, Ct, P, R     = lpeg.C, lpeg.Ct, lpeg.P, lpeg.R
local lpegmatch       = lpeg.match

local extract
do
  local digit     = R"09"
  local lower     = R"az"
  local comma     = P","
  local space     = P" "
  local schema    = Ct(   C(P"M")
                        * (digit^1 / tonumber)
                        * C(lower^1)
                        * (digit^1 / tonumber))
  local extractor = Ct((schema + 1)^0)
  extract = function (str)
    return lpegmatch (extractor, str)
  end
end

这将匹配输入的所有字符序列 由(按此顺序)

组成
  • 字母M
  • 一个或多个十进制数字的序列,
  • 一个包含1个或多个小写字符的序列,
  • 另一个包含1个或更多十进制数字的序列。

处理输入时,每个匹配都放在一个子表中, 数字在运行中转换为Lua数字。 由于问题请求,因此包括前导M 在条目中。

用法示例:

local data = extract [[M34a79 or M2ab943 or M4c4]]

for i = 1, #data do
  local elm = data[i]
  print (string.format ("[%d] = { [1] = %q, [2] = %d, [3] = %q, [4] = %d },",
                        i, table.unpack (elm)))
end

输出:

[1] = { [1] = "M", [2] = 34, [3] = "a", [4] = 79 },
[2] = { [1] = "M", [2] = 2, [3] = "ab", [4] = 943 },
[3] = { [1] = "M", [2] = 4, [3] = "c", [4] = 4 },

答案 2 :(得分:0)

解决方案:

http://www.coronalabs.com/blog/2013/04/16/lua-string-magic/

function string:split( inSplitPattern, outResults )
 ...
end

function val(x)
 x = x:gsub( "(%d)(%a)", "%1,%2" )
 x = x:gsub( "(%a)(%d)", "%1,%2" )

 Table = string.split(x,",")
 for i = 1, #Table do
   print( Table[i] ) 
 end
end

val("M3a5") 

返回M 3 a 5