Lua模式匹配用来“修复”HTML代码
2011-6-16 16:31:21
收藏:0
阅读:111
评论:2
我有很多格式不良的 HTML,我正在尝试使用 Lua 进行修复,例如
<p class='heading'>my useful information</p>
<p class='body'>lots more text</p>
我想用以下内容替换它
<h2>my useful information</h2>
<p class='body'>lots more text</p>
我想使用的是以下 Lua 函数,该函数接收整个 HTML 页面。但我有两个问题,我希望 gsub 将整个匹配(包括顶部和尾部)传递给 replace 函数,然后我将替换顶部和尾部并返回字符串。另一个问题是我的内部替换函数无法看到顶部和尾部字段。
如果这是一个显而易见的问题,我很抱歉,但我仍在学习 Lua。
function topandtailreplace(str, top, tail, newtop, newtail)
local strsearch = top .. '(.*)' .. tail
function replace(str)
str = string.gsub(str, top, newtop)
str = string.gsub(str, tail, newtail)
return str
end
local newstr = str:gsub(strsearch, replace())
return newstr
end
原文链接 https://stackoverflow.com/questions/6375349
点赞
stackoverflow用户1471119
你可以使用带有 DOM 树的 HTML 解析库,例如 lua-gumbo:
luarocks install gumbo
以下示例将实现你的需求:
local gumbo = require "gumbo"
local input = [[
<p class='heading'>my useful information</p>
<p class='body'>lots more text</p>
]]
local document = assert(gumbo.parse(input))
local headings = assert(document:getElementsByClassName("heading"))
local heading1 = assert(headings[1])
local textnode = assert(heading1.childNodes[1])
local new_h2 = assert(document:createElement("h2"))
heading1.parentNode:insertBefore(new_h2, heading1)
new_h2:appendChild(textnode)
heading1:remove()
io.write(document:serialize(), "\n")
2017-08-16 07:16:26
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
这似乎起作用了:
s=[[ <p class='heading'>我有用的信息</p> <p class='body'>更多的文字</p> ]] s=s:gsub("<p class='heading'>(.-)</p>","<h2>%1</h2>") print(s)