Reputation: 1174
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.
Upvotes: 5
Views: 10243
Reputation: 667
It's kinda late, but wondered the substring approach is missing in these answer. So thought of sharing my 2 cents...
-- utility function to trim the trailing/leading white-spaces
local function _trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
local decoded="username:password"
if decoded == nil then
decoded = ""
end
local iPos=string.find(decoded,":")
if iPos == nil then
iPos = #decoded
end
print(iPos)
local username = string.sub(decoded,1,iPos-1)
print("username:=["..username.."]") -- <== Here is the string before first occurance of colon
local password = string.sub(decoded,iPos+1)
password = _trim(password) -- Here is the rest of the string (will include other semi colons, if present)
print("password:=["..password.."]")```
Upvotes: 0
Reputation: 1356
Here, is easier than you think:
for s in string.gmatch("2233334;555555;12321315;2343242", "[^;]+") do
print(s)
end
Upvotes: 0
Reputation: 188
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.
Upvotes: 2
Reputation: 72312
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
Upvotes: 5