LUA split

2640阅读 0评论2019-12-06 khls27
分类:嵌入式

    关于字符串的分割,是一个非常非常常用的功能,笔者也很纳闷,LUA官方为何不在string库里予以支持?
    抱怨归抱怨,但问题还得解决,只能自己实现了。网上很多实现,但千篇一律,都不支多个字符分割且含有特殊字符的分割!

    比如: “abcxa.cxcba”,按“a.c”分割,那么网上绝大多数的实现是无法完成的,原因是“.”在lua字符串处理时,是一个特殊字符,需要转义。

    于是,笔者自己写了一段代码,优先对特殊字符进行转义,可以满足任意非空字符串分割符。实现如下:


点击(此处)折叠或打开

  1. split = function(str, sep)
  2.     if str == nil or str == "" or sep == nil or sep == "" then
  3.         return nil, "string and delimiter should NOT be empty"
  4.     end

  5.     local pattern = sep:gsub("[().%+-*?[^$]", "%%%1")
  6.     local result = {}
  7.     while str:len() > 0 do
  8.         local pstart, pend = string.find(str, pattern)
  9.         if pstart and pend then
  10.             if pstart > 1 then
  11.                 local subcnt = str:sub(1, pstart - 1)
  12.                 table.insert(result, subcnt)
  13.             end
  14.             str = str:sub(pend + 1, -1)
  15.         else
  16.             table.insert(result, str)
  17.             break
  18.         end
  19.     end
  20.     return result
  21. end

    代码写得比较直白(原始),各位看官自行优化。
上一篇:syslog 导致的死锁问题排查记录
下一篇:端口转发中的回流问题