首页 > 解决方案 > Lua - 从字符串中提取索引

问题描述

我有一个 lua 字符串 s1 ,如下所示。

s1='..{"login":{"username":"necs_0","url":"sip:192.168.1.218","contact":"sip:necs_0@192.168.1.218:61376","serverip":"192.168.1.216","serverport":"4080"}}';

显示为 .. 的前两个字节包含两个字节的大端格式长度。然后在 {"login":{"username":"necs_ 出现索引值0之后。我需要提取该索引值。

我写了下面的脚本,它有效。我想知道写它的最有效方法是什么。

s1='..{"login":{"username":"necs_0","url":"sip:192.168.1.218","contact":"sip:necs_0@192.168.1.218:61376","serverip":"192.168.1.216","serverport":"4080"}}';

-- Advance first two bytes
s2 = s1:sub(3);

-- Find the index of necs_
index1 = s2:find('necs_', 1, true);

-- Find the index of "
index2 = s2:find('"', index1, true);

-- Extract the data between necs_ and "
s3=string.sub(s2,index1+5,index2-1);

-- Print the extracted data
print(s3)

很少有让我担心的事情,在s2 = s1:sub(3)s2 中创建了一个新字符串,并将 s1 中的内容复制到新字符串 s2。在 C 的情况下,我可以做 like s2 = s1 + 2,因此我可以避免复制。

然后我正在使用findsubapi。有没有更有效的选择来做到这一点。

标签: lua

解决方案


推荐阅读