Lua模式匹配用来“修复”HTML代码

我有很多格式不良的 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用户107090
stackoverflow用户107090

这似乎起作用了:

s=[[
<p class='heading'>我有用的信息</p>
<p class='body'>更多的文字</p>
]]

s=s:gsub("<p class='heading'>(.-)</p>","<h2>%1</h2>")
print(s)
2011-06-16 16:55:42
stackoverflow用户1471119
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