lua - 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
,因此我可以避免复制。
然后我正在使用find
和sub
api。有没有更有效的选择来做到这一点。
解决方案
推荐阅读
- reactjs - React-Bootstrap-Typeahead - 如何组合选择
- php - 通过参数化查询登录不起作用
- python - curve_fit 包含 numpy 数组的 2D 函数 --> 形状 (3,3,9) 和 (3,1) 未对齐:9 (dim 2) != 3 (dim 0)
- c++ - c++ boost::multi_array 索引太大
- r - 在R中的用户定义函数中传递多个参数?
- html - 如何在网站中嵌入代码编辑器
- mysql - 为什么mysql查询不带引号很慢?
- node.js - $group by 之后的动态键
- python - 为什么'python --version'不打印字符串
- tomcat - 通过windows中的命令行在tomcat中部署war