Nic*_* M. 4 string lua lua-patterns
我有以下形式的字符串:
cake!apple!
apple!
cake!juice!apple!cake!
juice!cake!
Run Code Online (Sandbox Code Playgroud)
换句话说,这些字符串由三个子串"cake!"
,"apple!"
和"juice!"
.
我需要验证这些字符串.因此,使用正则表达式执行此操作的方法是:
/^(apple!|juice!|cake!)*$/
Run Code Online (Sandbox Code Playgroud)
但是Lua的模式没有|
运算符,所以它似乎无法以这种方式完成.
如何在Lua中验证我的字符串?
(我不关心字符串的内容:我只关心它们是否符合(验证).)
我知道编写代码来做到这一点,但我想不出一个简短的方法来做到这一点.我正在寻找一个简短的解决方案.我想知道是否有一个我不知道的优雅解决方案.有任何想法吗?
if str:gsub("%w+!", {["apple!"]="", ["juice!"]="", ["cake!"]=""}) == "" then
--do something
end
Run Code Online (Sandbox Code Playgroud)
此解决方案使用表作为第二个参数string.gsub
.由于模式都匹配%w+
,表将第二次验证,只有真正的三个模式被替换为空字符串.如果在所有替换后,字符串变空,则匹配成功.
使用辅助表变量可以使其更清晰:
local t = {["apple!"]="", ["juice!"]="", ["cake!"]=""}
if str:gsub("%w+!", t) == "" then
--do something
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
103 次 |
最近记录: |