gpt4 book ai didi

html - 使用 Lua 转义数字 XML 实体

转载 作者:数据小太阳 更新时间:2023-10-29 02:16:29 25 4
gpt4 key购买 nike

什么是取消转义数字 HTML/XML 实体的好实现,例如 并将它们替换为等效的 ASCII?

表示为单元测试:

local orig = "It's the "end" &ok;
"
local fixd = unescape(orig) -- Implement this
assert( fixd == "It's the \"end\" &ok;\n" )

最佳答案

下面是一个简单的实现,它也处理核心的命名 XML 实体:

function unescape(str)
str = string.gsub( str, '&lt;', '<' )
str = string.gsub( str, '&gt;', '>' )
str = string.gsub( str, '&quot;', '"' )
str = string.gsub( str, '&apos;', "'" )
str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others
return str
end

print(unescape("&#34;Hello&quot; &apos;World&#39;")) --> "Hello" 'World'

但是,请注意,对于一种病态情况,这会失败:数字和符号实体后跟文本 amp;:

print(unescape("Ampersand entity is &#38;amp;")) --> Ampersand entity is &
-- The result should actually be Ampersand entity is &amp;

我们可以通过一次处理所有实体来修复这种边缘情况,但代码会变得有点丑陋:

function unescape(str)
local map={ ["lt"]="<", ["gt"]=">", ["amp"]="&", ["quot"]='"', ["apos"]="'" }
str = string.gsub( str, '(&(#?x?)([%d%a]+);)', function(orig,n,s)
return (n=='' and map[s])
or (n=="#x" and tonumber(s,16)) and string.char(tonumber(s,16))
or (n=="#" and tonumber(s)) and string.char(s)
or orig
end )
return str
end

print(unescape("Ampersand entity is &#38;amp;")) --> Ampersand entity is &amp;

最后,我们可以打开它以提高一点速度:

local gsub, char = string.gsub, string.char
local entityMap = {["lt"]="<",["gt"]=">",["amp"]="&",["quot"]='"',["apos"]="'"}
local entitySwap = function(orig,n,s)
return (n=='' and entityMap[s])
or (n=="#" and tonumber(s)) and string.char(s)
or (n=="#x" and tonumber(s,16)) and string.char(tonumber(s,16))
or orig
end
function unescape(str)
return (gsub( str, '(&(#?x?)([%d%a]+);)', entitySwap ))
end

关于html - 使用 Lua 转义数字 XML 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14899734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com