lua 标签解析器
lua 标签解析器概述一个类xml标签解析函数,将标签解析成Lua中的表结构 原理使用lua的模式匹配,使用了模式串 要解析的字符串 hello world %26lt;div%26gt;hello world%26lt;/div%26gt; 你好 %26lt;div fontName='nihao' fontColor=#ffccdd%26gt;hello,world%26lt;/div%26gt; %26lt;div%26gt;%26lt;/div%26gt; 代码基本结构 -- 迭代所有格式为%26lt;xxx%26gt;的标签(包含了标签头和标签尾) local beginindex,endindex = string.find(text,"%b%26lt;%26gt;",1) while beginindex do -- 获得下一个标签的位置 beginindex,"%b%26lt;%26gt;",endindex) end 上面获得的beginindex和endindex分别是标签的在字符串中开始和结束的index值 但并不区分标签头和标签尾, -- 获得当前标签,字符串截取出来 local label = string.sub(text,beginindex,endindex) -- 判断当前标签是不是以'%26lt;/'开头,若是以'%26lt;/'开头则代表为标签尾巴,否则为标签头 if string.find(label,"^%26lt;/") then else end 至此已经可以在正确的从字符串中提取所有的标签,并且区分出标签头和标签尾了 处理标签匹配问题 我们没有考虑特殊情况,若字符串最完成不是标签那最外层处理会存在点问题。 现在我们解析出了内容和修饰内容的标签,离成功不远了!! 解析标签头 第一步 local labelnameindex1,labelnameindex2 = string.find(label,"%w+") 因为我们要解析的串大多是手写,为了减小书写难度,标签名属性名最好不区分大小写 -- 获得标签名称 local labelname = string.sub(label,labelnameindex1,labelnameindex2) labelname = string.lower(labelname) 第二步 -- value要求非空白字符并且不含有'%26gt;'字符的一个单词 string.gmatch(labelhead,"%w+%=[^%s%%26gt;]+") gmatch会返回一个迭代器,每次运行都返回一个匹配串,所以我们这么写 for property in string.gmatch(labelhead,"%w+%=[^%s%%26gt;]+") do end 在循环中我们可以处理每个属性对字符串无非就是根据 local equalmarkpos = string.find(property,"=") -- 分离属性名和属性值 local propertyname = string.sub(property,1,equalmarkpos-1) local propertyvalue = string.sub(property,equalmarkpos+1,string.len(property)) -- 属性名转为小写 propertyname = string.lower(propertyname) -- 属性值处理 local continue = false -- 1.检测是否为字符串(单引号或者双引号括起来) local beginindex,endindex = string.find(propertyvalue,"['"].+['"]") if beginindex then propertyvalue = string.sub(propertyvalue,beginindex+1,endindex-1) continue = true end -- 2.检测是否为布尔值 if not continue then local propertyvalue_lower = string.lower(propertyvalue) if propertyvalue_lower == BOOLEAN_TRUE then propertyvalue = true continue = true elseif propertyvalue_lower == BOOLEAN_FALSE then propertyvalue = false continue = true end end -- 3.检测是否为数字 if not continue then local propertyvalue_number = tonumber(propertyvalue) if propertyvalue_number then propertyvalue = propertyvalue_number continue = true end end -- 若以上都不是,则默认直接为字符串 labelparams[propertyname] = propertyvalue 顺便吐槽一下 最后完整代码在我的github上面叫labelparser,lua5.1解析器可以直接运行,无需任何依赖 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |