LUA中是否有函数可以替换字符串上的值,但要保留一部分原始值?

发布于 2025-02-06 02:01:10 字数 274 浏览 4 评论 0原文

我正在尝试获得一个类似的字符串: “ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时常饿 2025-02-13 02:01:11

这样的模式仅仅是“一个或多个数字,然后是字母d,然后是一个或多个数字”。用包裹在字符串文字上的捕获&替换为& func调用rolar

str:gsub("%d+d%d+", "rolar('%1')")

其中str是您的字符串 - 例如:(

> ("1d6+1d12-1d20+5"):gsub("%d+d%d+", "rolar('%1')")
rolar('1d6')+rolar('1d12')-rolar('1d20')+5  3

第二个返回值,3gsub;您大概是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 to rolar.

str:gsub("%d+d%d+", "rolar('%1')")

where str is your string - for example:

> ("1d6+1d12-1d20+5"):gsub("%d+d%d+", "rolar('%1')")
rolar('1d6')+rolar('1d12')-rolar('1d20')+5  3

(the second return value, 3, is the number of replacements performed by gsub; 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 like while 1 do end, but at least it doesn't make it trivial to wipe your filesystem.

朕就是辣么酷 2025-02-13 02:01:11

如果您肯定输入始终处于这样的配置中,则可以使用捕获组(围绕字符串模式)使用GSUB进行此操作。

str:gsub("(%d+d%d+)", function(roll) return "rolar('"..roll.."')" end)

捕获的模式%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).

str:gsub("(%d+d%d+)", function(roll) return "rolar('"..roll.."')" end)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文