在Lua中如何按/字符分割长字符串并将拆分结果存入表
你使用的gmatch匹配规则([/])(.-)%1要求目标片段前后必须被/包裹,原字符串的首段Hello前方无/、尾段Hi后方无/,因此无法被完整捕获,只会返回前后都有/包裹的中间段内容。
最简修复方案
直接修改匹配规则为[^/]+即可,该规则会匹配所有连续的非/字符序列,正好符合按/分割的需求:
local STR = "Hello/GoodBye/Hi" local strings = {} for seg in STR:gmatch("[^/]+") do table.insert(strings, seg) end
运行后strings表就会按顺序存入Hello、GoodBye、Hi三个值。
通用兼容方案
如果需要处理首尾带分隔符、分隔符连续的场景(例如字符串为/a//b/,需要保留空片段),可以使用手动遍历索引的分割函数:
local function split(str, sep) sep = sep or "/" local res = {} local start_idx = 1 local sep_start, sep_end = str:find(sep, start_idx) while sep_start do table.insert(res, str:sub(start_idx, sep_start - 1)) start_idx = sep_end + 1 sep_start, sep_end = str:find(sep, start_idx) end table.insert(res, str:sub(start_idx)) return res end -- 调用示例 local STR = "Hello/GoodBye/Hi" local strings = split(STR)
内容的提问来源于stack exchange,提问作者Beemo
相关产品推荐
相关产品推荐

