Lua:如何替换两个或多个重复的“?"带有空字符串的字符? [英] Lua: How do I replace two or more repeating "?" characters with an empty string?
本文介绍了Lua:如何替换两个或多个重复的“?"带有空字符串的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了以下操作:
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.
例如:
"?" = not replaced
"??" = replaced
"???" = replaced
任何帮助将不胜感激.
推荐答案
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).
此代码
function test(s)
print(s,s:gsub("%?%?+","-"))
end
for n=0,4 do
test("["..string.rep("?",n).."]")
end
输出
[] [] 0
[?] [?] 0
[??] [-] 1
[???] [-] 1
[????] [-] 1
其中-
显示替换的位置.
这篇关于Lua:如何替换两个或多个重复的“?"带有空字符串的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文