【问题标题】:Lua split string by semicolonLua用分号分割字符串
【发布时间】:2017-05-18 17:17:35
【问题描述】:

如何在 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 脚本的新手,所以无法获得准确的语法。

【问题讨论】:

  • destination_number:gmatch '(%d+);?'。如果您也需要字母,请替换为%w
  • 这里和整个网络都多次询问和解释字符串拆分。
  • 如果以下答案之一对您有用,请采纳。

标签: split lua


【解决方案1】:

如果你只想要 first 出现,那么这行得通:

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

模式如下:直到第一个分号,但不包括第一个分号。

如果你想要所有的出现,那么这行得通:

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

【讨论】:

  • a;;c;d 怎么样?第二个字符串暗示存在并且等于空字符串。这种情况在 CSV 文件中很常见
  • @EgorSkriptunoff,当然。 OP 需要更准确地定义问题。
【解决方案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 是包含这些数字的表格。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 2014-07-14
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      相关资源
      最近更新 更多