如何在Lua中用一个单词替换多个符号?
我必须替换所有这些字符,”①②③④⑤⑥⑦⑧⑨⑩", 带有“\item” 我使用了以下代码:如何在Lua中用一个单词替换多个符号?,lua,replace,Lua,Replace,我必须替换所有这些字符,”①②③④⑤⑥⑦⑧⑨⑩", 带有“\item” 我使用了以下代码: stra = string.gsub(text, "①", "\\item") strb = string.gsub(stra, "②", "\\item") strc = string.gsub(strb, "③", "\\item") strd = string.gsub(strc, "④", "\\item") stre = string.gsub(strd,
stra = string.gsub(text, "①", "\\item")
strb = string.gsub(stra, "②", "\\item")
strc = string.gsub(strb, "③", "\\item")
strd = string.gsub(strc, "④", "\\item")
stre = string.gsub(strd, "⑤", "\\item")
但是,这非常冗长。有没有更简单的方法来替换所有这些项目?使用教程中描述的“集合”:
有没有更简单的方法来替换所有这些项目
没有知道UTF-8是什么的Lua模式匹配库是不行的。Lua不知道Unicode;它不知道如何搜索Unicode符号
如果您使用的是一些非多字节编码,那么John的建议可能会起作用,但如果是UTF-8就不行了
对于您的具体情况,您始终可以这样做:
local symbolsToChange { "①", "②", ...}
for i, sym in ipairs(symbolsToChange) do
string.gsub(text, sym, "\\item")
end
或者如果您想将它们全部替换为“\\item”
:
[\160-\169]
相当于[\160\161\162\163\164\165\166\167\168\169]
。
有关范围和Lua模式的信息,请参见
你也可以想象:
text = string.gsub(text,
"\266\145([\160-169])",
function(c)
return "\\item"..(string.byte(c)-160+1)
end
)
这将变成
①代码>进入\item1
,②
转换为\item2
,依此类推。应该注意的是,Lua不处理Unicode。即使这些是UTF-8字符串,Lua也不会知道。它会按原样查找每个UTF-8代码单元。原始代码工作的唯一原因是因为Lua在查找代码单元的序列。您在上面发布的内容将查找每个代码单元反过来又是。
local symbols_trans = {
["\226\145\160"]--[[①]] = "\\item1",
["\226\145\161"]--[[②]] = "\\bananas",
["\226\145\162"]--[[③]] = "\\cactus",
["\226\145\163"]--[[④]] = "\\etc",
["\226\145\164"]--[[⑤]] = "\\item5",
["\226\145\165"]--[[⑥]] = "\\item6",
["\226\145\166"]--[[⑦]] = "\\item7",
["\226\145\167"]--[[⑧]] = "\\item8",
["\226\145\168"]--[[⑨]] = "\\item9",
["\226\145\169"]--[[⑩]] = "\\item10",
}
text = string.gsub(text, "(\266\145.)", symbol_trans)
text = string.gsub(text,
"\266\145[\160-\169]",
"\\item"
)
text = string.gsub(text,
"\266\145([\160-169])",
function(c)
return "\\item"..(string.byte(c)-160+1)
end
)