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脚本是新手,所以无法得到准确的语法。

原文链接 https://stackoverflow.com/questions/41463421

点赞
stackoverflow用户107090
stackoverflow用户107090

如果你只想要第一次出现的字符串,那么可以用如下代码:

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

这个匹配规则是:从开头到第一个分号出现前的所有字符。

如果你想要所有出现的字符串,可以使用这段代码:

for token in string.gmatch(destination_number, "[^;]+") do
    print(token)
end
2017-01-04 15:35:52
stackoverflow用户7623834
stackoverflow用户7623834

希望这段代码能对您有所帮助:

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

--[[ 输出:
2233334
555555
12321315
2343242
]]

现在,result是一个表,其中包含这些数字。

2017-03-05 11:23:48
stackoverflow用户7347992
stackoverflow用户7347992

以下是中文翻译,同时保留了原始的 markdown 格式:

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

对于变量 s 在字符串 "2233334;555555;12321315;2343242" 中,按照 "[^;]+" 的规则匹配,循环输出匹配到的 s 值。
2018-05-21 05:01:55
stackoverflow用户1751166
stackoverflow用户1751166

有点晚了,但是想指出这些答案中缺少子字符串方法。所以想分享一下我的想法...

-- 工具函数,用于修剪字符中的首尾空格
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.."]") -- <== 这里是第一个冒号前的字符串
local password = string.sub(decoded,iPos+1)
password = _trim(password) -- 这里是字符串的剩余部分(如果有其他半个冒号之类的话)
print("password:=["..password.."]")```
2022-05-18 22:41:54