Lua pattern <li> html 标签



我想提取li元素中的值,并将它们存储到变量中。

示例:

<li>Male</li><li>Hustisford, WI</li><li>United States</li>

然而,它也可能是这样的:

<li>Hustisford, WI</li><li>United States</li>

或否

我从这个开始:

author_origin = string.gsub(string.gsub(htmlcode,"<li>","#"),"</li>","|")
author_gender, author_orig_city, author_orig_country = string.match(author_origin,"#(.-)|#(.-)|#(.-)|") 

=>这对第一个例子有效,但对其他情况无效。

我以为它应该是这样的,但它没有起作用:

author_gender, author_orig_city, author_orig_country = string.match(author_origin,"[#]?(.-?)[|]?[#]?(.-?)[|]?[#]?(.-?)[|]?")

您可以通过简单地获取所有符合您的标准的东西,然后在最后弄清楚您拥有什么,来避免需要多个模式。像这样的东西。

function extract(s)
    local t = {}
    for v in s:gmatch("<li>(.-)</li>") do
        t[#t + 1] = v
    end
    if #t == 3 then
        return (unpack or table.unpack)(t)
    end
    return nil,(unpack or table.unpack)(t)
end
author_gender, author_orig_city, author_orig_country = extract("<li>Male</li><li>Hustisford, WI</li><li>United States</li>")
print(author_gender, author_orig_city, author_orig_country)
author_gender, author_orig_city, author_orig_country = extract('<li>Hustisford, WI</li><li>United States</li>')
print(author_gender, author_orig_city, author_orig_country)

你不能用一个模式来完成。你需要两个。首先尝试三个字段。如果失败,请尝试两个字段。而且您不需要用其他字符替换HTML标记。

author_gender, author_orig_city, author_orig_country = string.match(author_origin,"<li>(.-)</li><li>(.-)</li><li>(.-)</li>")
if author_gender==nil then
   author_orig_city, author_orig_country = string.match(author_origin,"<li>(.-)</li><li>(.-)</li>")
end

如果您需要解析不可预测的HTML,并且不介意依赖库,您可以使用lua-gumbo:

local gumbo = require "gumbo"
local input = "<li>Male</li><li>Hustisford, WI</li><li>United States</li>"
local document = gumbo.parse(input)
local elements = document:getElementsByTagName("li")
local gender = elements[1].textContent
local city = elements[2].textContent
local country = elements[3].textContent
print(gender, city, country)

最新更新