我必须将这些字符“①②③④⑤⑥⑦⑧⑧⑨⑩”全部替换为“\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, "⑤", "\\item")
但是,这是非常冗长的。有没有更简单的方法来替换所有这些项目?
最佳答案
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)
或者如果您想将它们全部替换为"\\item"
:
text = string.gsub(text,
"\266\145[\160-\169]",
"\\item"
)
[\160-\169]
等同于 [\160\161\162\163\164\165\166\167\168\169]
。
查看Lua manual有关范围和一般 Lua 模式的信息。
你也可以很花哨:
text = string.gsub(text,
"\266\145([\160-169])",
function(c)
return "\\item"..(string.byte(c)-160+1)
end
)
这会将①
变成\item1
,②
变成\item2
,等等。
关于lua - 如何在 Lua 中用一个单词替换多个符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059427/