【问题标题】:Lua Pattern Matching to "fix" html codeLua 模式匹配以“修复”html 代码
【发布时间】:2011-09-16 13:11:28
【问题描述】:

我有很多格式错误的 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 将替换函数传递给整个匹配项,包括顶部和尾部,然后我将替换顶部和尾部并返回字符串。另一个问题是我的内部替换功能看不到顶部和尾部字段。

对不起,如果这是一个明显的问题,但我仍在学习 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

【问题讨论】:

    标签: string lua design-patterns


    【解决方案1】:

    这似乎有效:

    s=[[
    <p class='heading'>my useful information</p>
    <p class='body'>lots more text</p>
    ]]
    
    s=s:gsub("<p class='heading'>(.-)</p>","<h2>%1</h2>")
    print(s)
    

    【讨论】:

    • 非常感谢,我试图让它变得更难,我完全错过了保留中间位的 %1 选项。
    【解决方案2】:

    您可以使用带有 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")
    

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2017-01-19
      • 2013-01-19
      • 1970-01-01
      • 2019-03-29
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多