【问题标题】:String with Numbers to Table带数字的字符串到表格
【发布时间】:2020-10-23 01:29:27
【问题描述】:

如何转换以下字符串:

string = "1,2,3,4"

进入表格:

table = {1,2,3,4}

感谢您的帮助;)

【问题讨论】:

  • 这能回答你的问题吗? Split a string using string.gmatch() in Lua
  • 不,我尝试了 string.gmatch,但它转换了table = {"1,2,3,4"} 中的表格我只想要table = {1,2,3,4},不带引号
  • 等一下,我找到了如何做到这一点:t = {}; s = "1,2,3,4" for w in (s .. ","):gmatch("([^,]*),") do table.insert(t, w) end for k, v in pairs(t) do tonumber(t[k]) end 已解决!谢谢你
  • @droppels - 不要忘记tonumber这些你现在在表格中的字符串
  • @droppels 这个模式([^,]*), 将错过最后一个条目。例如,如果输入是1,2,3,4,则4 没有后续,,并且与模式不匹配,将被排除。

标签: lua


【解决方案1】:

让 Lua 做艰苦的工作:

s="1,2,3,4"
t=load("return {"..s.."}")()
for k,v in ipairs(t) do print(k,v) end

【讨论】:

    【解决方案2】:

    以下是从 Scribunto 扩展改编为 MediaWiki 的代码。它允许在可以长于一个字符的模式上拆分字符串。

    -- Iterator factory
    function string:gsplit (pattern, plain)
        local s, l = 1, self:len()
        return function ()
            if s then
                local e, n = self:find (pattern, s, plain)
                local ret
                if not e then
                    ret = self:sub (s)
                    s = nil
                elseif n < e then
                    -- Empty separator!
                    ret = self:sub (s, e)
                    if e < l then
                        s = e + 1
                    else
                        s = nil
                    end
                else
                    ret = e > s and self:sub (s, e - 1) or ''
                    s = n + 1
                end
                return ret
            end
        end, nil, nil
    end
    
    -- Split function that returns a table:
    function string:split (pattern, plain)
        local ret = {}
        for m in self:gsplit (pattern, plain) do
            ret [#ret + 1] = m
        end
        return ret
    end
    
    -- Test:
    local str = '1,2, 3,4'
    print ('table {' .. table.concat (str:split '%s*,%s*', '; ') .. '}')
    
    

    【讨论】:

      【解决方案3】:

      您可以使用gmatch 和模式(%d+) 创建一个迭代器,然后填充表格。

      local input = "1,2,3,4"
      local output = {}
      
      for v in input:gmatch("(%d+)") do
        table.insert(output, tonumber(v))
      end
      
      for _,v in pairs(output) do
        print(v)
      end
      

      (%d+) 模式将捕获任意数量的数字 (0-9)。

      这是一个狭义的解决方案,它不处理诸如

      之类的空白条目
      input = "1,2,,4"
      output = {1,2,4}
      

      它也不关心分隔符是什么,或者它是否对每个条目都一致。

      input = "1,2 3,4"
      output = {1,2,3,4}
      

      参考:

      Lua 5.3 Manual, Section 6.4 – String Manipulation: string.gmatch

      FHUG: Understanding Lua Patterns

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 2012-06-14
        相关资源
        最近更新 更多