Lua分号分隔字符串
2017-1-4 23:16:27
收藏:0
阅读:87
评论: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脚本是新手,所以无法得到准确的语法。
原文链接 https://stackoverflow.com/questions/41463421
点赞
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
以下是中文翻译,同时保留了原始的 markdown 格式:
这里,比你想象的更容易:
对于变量 s 在字符串 "2233334;555555;12321315;2343242" 中,按照 "[^;]+" 的规则匹配,循环输出匹配到的 s 值。
2018-05-21 05:01:55
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
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
如果你只想要第一次出现的字符串,那么可以用如下代码:
print(string.match(destination_number, "(.-);"))
这个匹配规则是:从开头到第一个分号出现前的所有字符。
如果你想要所有出现的字符串,可以使用这段代码:
for token in string.gmatch(destination_number, "[^;]+") do print(token) end