LUA中是否有函数可以替换字符串上的值,但要保留一部分原始值?
我正在尝试获得一个类似的字符串: “ 1d6+1d12-1d20+5”
,然后将其转换为:“ rolar('1d6')+rolar('1d12') - rolar('1d20')+5“) /代码>
要点是XDY
应替换为rolar('xdy')
,但该部分中的原始值。我一直在尝试使用string:gsub
来完成此操作,但无法使用原始的XDY值来完成此操作。
I'm trying to get a string like:"1d6+1d12-1d20+5"
And turn it into this: "rolar('1d6')+rolar('1d12')-rolar('1d20')+5"
The gist being that the xdy
should be replaced with rolar('xdy')
but with the original value in that part. I've been trying to do this with string:gsub
but haven't been able to mantain the original xdy value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样的模式仅仅是“一个或多个数字,然后是字母
d
,然后是一个或多个数字”。用包裹在字符串文字上的捕获&替换为& func调用rolar
。其中
str
是您的字符串 - 例如:(第二个返回值,
3
是gsub
;您大概是Don的替换次数't需要它)我认为您的下一步将是
loadString
此代码以评估它。 这样做时要非常小心;至少使用沙盒环境(即,即使暂时更改的字符串METATAT,也无需访问任何全局变量的环境)。这也不会防止这样的简单DOS攻击,而1确实结束了
,但至少擦除文件系统并不容易。The pattern for this is simply "one or more digits, then the letter
d
, then again one or more digits". Replace this with the capture wrapped in a string literal & func call torolar
.where
str
is your string - for example:(the second return value,
3
, is the number of replacements performed bygsub
; you presumably don't need it)I assume your next step will be to
loadstring
this code in order to evaluate it. Be very careful when doing so; at the very least use a sandboxed environment (i.e., an environment without access to any global variables, ideally even with a temporarily changed string metatable). This won't protect against even simple DoS attacks likewhile 1 do end
, but at least it doesn't make it trivial to wipe your filesystem.如果您肯定输入始终处于这样的配置中,则可以使用捕获组(围绕字符串模式)使用GSUB进行此操作。
捕获的模式
%d+d%d
传递给您给GSUB的函数作为参数,然后您可以使用所需的任何修改将其重新插入字符串中。If you're positive that the input will always be in a configuration like that, you can do this with gsub, using capture groups (parentheses around string patterns).
The captured pattern
%d+d%d
is passed to the function you give to gsub as an argument, and you can then re-insert back into the string with whatever modifications you want.