问题
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