Lua用分号分割字符串

时间:2017-01-04 12:05:27

标签: split lua

如何用分号在Lua中拆分字符串?

local destination_number="2233334;555555;12321315;2343242"

这里我们可以看到多次出现分号(;)但我只需要在第一次出现之前从上面的字符串输出。

尝试过的代码:

if string.match(destination_number, ";") then
    for token in string.gmatch(destination_number, "([^;]+),%s*") do
        custom_destination[i] = token
        i = i + 1

    end 
end

输出:

2233334

我已经尝试过上面的代码,但新手到Lua脚本,所以无法获得准确的语法。

3 个答案:

答案 0 :(得分:2)

如果你只想要第一次,那么这就有效:

print(string.match(destination_number, "(.-);"))

该模式显示:所有内容均为第一个分号,但不包括第一个分号。

如果你想要所有的出现,那么这是有效的:

for token in string.gmatch(destination_number, "[^;]+") do
    print(token)
end

答案 1 :(得分:0)

我希望此代码能为您提供帮助:

function split(source, sep)
    local result, i = {}, 1
    while true do
        local a, b = source:find(sep)
        if not a then break end
        local candidat = source:sub(1, a - 1)
        if candidat ~= "" then 
            result[i] = candidat
        end i=i+1
        source = source:sub(b + 1)
    end
    if source ~= "" then 
        result[i] = source
    end
    return result
end

local destination_number="2233334;555555;12321315;2343242"

local result = split(destination_number, ";")
for i, v in ipairs(result) do
    print(v)
end

--[[ Output:
2233334
555555
12321315
2343242
]]

现在result是包含这些数字的表格。

答案 2 :(得分:0)

在这里,比你想象的容易:

for s in string.gmatch("2233334;555555;12321315;2343242", "[^;]+") do
    print(s)
end
相关问题