Lua通过分号拆分字符串

4

如何在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脚本语言还是新手,无法得到精确的语法。


1
如果您需要字母,可以使用“%w”替换为“destination_number:gmatch'(%d +);?'”。 - greatwolf
字符串分割在这里和整个网络中已经被问及和解释了很多次。 - warspyking
如果下面的任何答案对您有用,请接受它。 - R. Gadeev
4个回答

4
如果你只想要第一个出现的结果,那么这样做是有效的:
print(string.match(destination_number, "(.-);"))

该模式的意思是:匹配第一个分号之前的所有字符,但不包括分号本身。
如果你想匹配所有出现的情况,则可以使用以下方法:
for token in string.gmatch(destination_number, "[^;]+") do
    print(token)
end

2
a;;c;d是什么情况?第二个字符串被暗示为存在且等于空字符串。这种情况在CSV文件中非常常见。 - Egor Skriptunoff
@EgorSkriptunoff,好的。原帖需要更精确地定义问题。 - lhf

2
我希望这段代码能够帮助你:
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 是一个包含这些数字的表格。

0

可能有点晚了,但我想这些答案中缺少了子字符串的方法。所以我想分享我的意见...

-- 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.."]")```

0

这里比你想象的要容易:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接