此功能允许您从两个字符串分隔符之间提取文本:
function get_text (str, init, term)
local _, start = string.find(str, init)
local stop = string.find(str, term)
local result = nil
if _ and stop then
result = string.sub(str, start + 1, stop - 1)
end
return result
end
示例交互:
> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg, "<action>", "<SetVolume>")
Play</action>
> get_text(msg, "<action>", "</SetVolume>")
Play</action><SetVolume>5
这是对上述函数的修改,允许nil 用于参数init 或term。如果init 是nil,则提取文本直到term 分隔符。如果term 是nil,则从init 之后到字符串末尾提取文本。
function get_text (str, init, term)
local _, start
local stop = (term and string.find(str, term)) or 0
local result = nil
if init then
_, start = string.find(str, init)
else
_, start = 1, 0
end
if _ and stop then
result = string.sub(str, start + 1, stop - 1)
end
return result
end
示例交互:
> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg)
<action>Play</action><SetVolume>5</SetVolume>
> get_text(msg, nil, '<SetVolume>')
<action>Play</action>
> get_text(msg, '</action>')
<SetVolume>5</SetVolume>
> get_text(msg, '<action>', '<SetVolume>')
Play</action>