Chinaunix首页 | 论坛 | 博客
  • 博客访问: 742652
  • 博文数量: 141
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1115
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-17 14:32
个人简介

小公司研发总监,既当司令也当兵!

文章分类

全部博文(141)

分类: 嵌入式

2019-12-06 11:01:49

    关于字符串的分割,是一个非常非常常用的功能,笔者也很纳闷,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

    代码写得比较直白(原始),各位看官自行优化。
阅读(2726) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~