4
votes

How to split string in Lua by semicolon?

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

Here we can see that multiple times occurrence of semicolon (;) but I need output from above string only before first occurrence.

Tried code :

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

    end 
end

Output :

2233334

I have tried above code but newbie to Lua scripting so can't get exact syntax for that.

3
destination_number:gmatch '(%d+);?'. Replace with %w if you need letters too. - greatwolf
String splitting has been asked and explained many times throughout here and throughout the web. - warspyking
If one of the answers below was useful to you then accept it please. - R. Gadeev

3 Answers

4
votes

If you just want the first occurrence, then this works:

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

The pattern reads: everything up to, but not including, the first semicolon.

If you want all occurrences, then this works:

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

I hope this code will help you:

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
]]

Now result is table which contains these numbers.

0
votes

Here, is easier than you think:

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