# lua 模式匹配进阶

2016/05/30 19:17

local teststr = "##3325#欢迎#00来到###g#N高小恩0#0制作#w游戏#g牛逼#0x000ff0006#g###w房间#g大神F1#w   服务费:赞一枚3Q#445"

--local teststr = "#g牛逼的人生#p不牛逼#g牛逼#gjkjk#p"

local ruleTbl = {}

-- 基本思路如下：

-- 先找到#位置，然后向后取8位

-- 根据优先级来判断是否是怎么的取值（先是16定制，再是颜色，再是数字）

local fidx = 0

local lidx = 0

local xflag = false  -- 已经匹配了十六定制的值

local zflag = false  -- 已经匹配了字母的值

for ss in string.gfind(teststr,"#") do

xflag = false

zflag = false

fidx,lidx = string.find(teststr,ss,lidx+1)

local temp_str = string.sub(teststr,fidx,fidx+10)

--print(temp_str)

for ss in string.gfind(temp_str,"#0x%x%x%x%x%x%x%x%x") do

xflag = true

print("匹配到了十六定制的值")

print(temp_str)

table.insert(ruleTbl,{value=ss,fidx = fidx, lidx = fidx+10, type= "color" })

end

if xflag then

else      -- 匹配单字母的颜色定义

local temp_str = string.sub(teststr,fidx,fidx+1)

for ss in string.gfind(temp_str,"#%a") do

print("匹配字母颜色")

print(temp_str)

zflag = true

if ss == "N" then

print("此处用来判断，没用的字母定义无效")

else

table.insert(ruleTbl,{value=ss,fidx = fidx, lidx = fidx+1, type= "color"})

end

end

if zflag then

--print("匹配到了字母颜色了")

else  -- 匹配图片包括一位，两位，三位

--print("开始匹配数字情况")

local numcount = 3

while (numcount >0) do

local threeflag = false

local twoflag   = false

local oneflag   = false

local temp_str = string.sub(teststr,fidx,fidx+numcount)

print("开始匹配数字")

print(temp_str)

if numcount == 3 then

for ss in string.gfind(temp_str,"#%d%d%d") do

print("匹配三位数图片")

threeflag = true

table.insert(ruleTbl,{value=ss,fidx = fidx, lidx = fidx+3 ,type= "image"})

end

if threeflag then

break

end

end

if numcount == 2 then

for ss in string.gfind(temp_str,"#%d%d") do

print("匹配2位数图片")

twoflag = true

table.insert(ruleTbl,{value=ss,fidx = fidx, lidx = fidx+2 ,type= "image"})

end

if twoflag then

break

end

end

if numcount == 1 then

for ss in string.gfind(temp_str,"#%d") do

print("匹配1位数图片")

oneflag = true

table.insert(ruleTbl,{value=ss,fidx = fidx, lidx = fidx+1 ,type= "image"})

end

if oneflag then

break

end

end

numcount = numcount - 1

end

end

end

end

print("感谢牛逼的牛逼想法！！")

0
0 收藏

0 评论
0 收藏
0