Lua: How do I replace two or more repeating “?” characters with an empty string?

守給你的承諾、 提交于 2021-02-10 14:17:47

问题


I've tried something like the following:

local str = "???"
string.gsub(str, "(??)*", "")

but it removes all '?' characters. I'd like single '?' not replaced but more than one '?' replaced with an empty string.

Eg:

"?" = not replaced
"??" = replaced
"???" = replaced

Any help would be greatly appreciated.


回答1:


Question marks are magic in Lua patterns: they mean 0 or 1 occurrence of the previous class. Lua escapes magic characters in patterns with the % character.

The correct pattern for your task is %?%?+, which means an actual ? character once, followed by one or more actual ? characters (see the + modifier in the link above).

This code

function test(s)
    print(s,s:gsub("%?%?+","-"))
end

for n=0,4 do
    test("["..string.rep("?",n).."]")
end

outputs

[]      []      0
[?]     [?]     0
[??]    [-]     1
[???]   [-]     1
[????]  [-]     1

where - shows where replacements were made.



来源:https://stackoverflow.com/questions/51317085/lua-how-do-i-replace-two-or-more-repeating-characters-with-an-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!