0基础lua学习(二十一)分割字符串逗号

[ Lua ] 专栏收录该内容
22 篇文章 0 订阅

 

1.使用正则表达式分割

 

 

 starNum =  "asd,dfg,ghj"

resultStrList = {}
	reps = ","
	--  [^,]+ 正则表达式 匹配,

    string.gsub(starNum,'[^'..reps..']+',function ( w )
        table.insert(resultStrList,w)
    end)

	print(resultStrList[1])
	print(resultStrList[2])
	print(resultStrList[3])

 

 

 

console:

>lua -e "io.stdout:setvbuf 'no'" "base.lua"
asd
dfg
ghj
>Exit code: 0

 

2.

 


    input = "123,456,789"
    delimiter = ","
    if (delimiter=='') then return false end
    local pos,arr = 0, {}
    for st,sp in function() return string.find(input, delimiter, pos, true) end do
        table.insert(arr, string.sub(input, pos, st - 1))
        pos = sp + 1
    end
    table.insert(arr, string.sub(input, pos))
	print(arr[1])
	print(arr[2])
	print(arr[3])

 

 

 

 

 

console:

123
456
789
>Exit code: 0
 

3.

 

 

	breakpointsStr = ","
	logStr = "123,456,12312313"
	local i = 0
    local j = 1
	t = {}
    local z = string.len(breakpointsStr)
    while true do
        i = string.find(logStr, breakpointsStr, i + 1)  -- 查找下一行
        if i == nil then
            table.insert(t, string.sub(logStr,j,-1))
            break
        end
        table.insert(t, string.sub(logStr,j,i - 1))
        j = i + z

    end
	print(t[1])
	print(t[2])
	print(t[3])


console:

 

>lua -e "io.stdout:setvbuf 'no'" "base.lua"
123
456
12312313
>Exit code: 0

 

  • 0
    点赞
  • 1
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值