lua字符串分割

这篇博客介绍了在Lua中如何使用函数`gsplit`和`split`对字符串进行按模式分割。`gsplit`函数是一个迭代器,允许遍历由指定模式分隔的字符串子串,而`split`函数则返回一个包含所有子串的表。这两个函数都接受一个文本字符串、分隔模式以及是否将模式解释为普通字符串的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

– gsplit: iterate over substrings in a string separated by a pattern

– Parameters:
– text (string) - the string to iterate over
– pattern (string) - the separator pattern
– plain (boolean) - if true (or truthy), pattern is interpreted as a plain
– string, not a Lua pattern

– Returns: iterator

– Usage:
– for substr in gsplit(text, pattern, plain) do
– doSomething(substr)
– end
local function gsplit(text, pattern, plain)
local splitStart, length = 1, #text
return function ()
if splitStart then
local sepStart, sepEnd = string.find(text, pattern, splitStart, plain)
local ret
if not sepStart then
ret = string.sub(text, splitStart)
splitStart = nil
elseif sepEnd < sepStart then
– Empty separator!
ret = string.sub(text, splitStart, sepStart)
if sepStart < length then
splitStart = sepStart + 1
else
splitStart = nil
end
else
ret = sepStart > splitStart and string.sub(text, splitStart, sepStart - 1) or ‘’
splitStart = sepEnd + 1
end
return ret
end
end
end

– split: split a string into substrings separated by a pattern.

– Parameters:
– text (string) - the string to iterate over
– pattern (string) - the separator pattern
– plain (boolean) - if true (or truthy), pattern is interpreted as a plain
– string, not a Lua pattern

– Returns: table (a sequence table containing the substrings)
local function split(text, pattern, plain)
local ret = {}
for match in gsplit(text, pattern, plain) do
table.insert(ret, match)
end
return ret
end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值