用于识别 XdY+Z OR XdY 的正则表达式

标签 regex lua

我一直在尝试开发一个程序,用于在 MMORPG 中进行 DMing,但在解析我需要的实际正则表达式时遇到问题。

引用我自己在不太活跃的论坛上的另一个帖子:

I've officially taken over the DiceRoller addon from years and years ago and I've reworked it a lot since I've taken it over and done a lot of testing in game. While I haven't uploaded anything yet, I've been struggling on a piece of regex expression that is currently crucial to the design of the addon.

Some background: the newest iteration of the DiceRoller addon makes it so you can type "!XdY" (where X is the number of dice, Y is the dice value) into raid chat and the DM who has the addon will go through some logic in the addon (random number lua protocol) and then spit out an input after adding up the dice.

It is as follows:

local count, size = string.match(message, "^!(%d+)[dD](%d+)$")

Now the functionality I need it to do is parse for both "!XdY" OR "XdY+Z", but it seems as if I can't get close to "XdY+Z" no matter which regex expression I use since I need it to do both expressions. I can provide more source code context if necessary.

This is the closest I've ever gotten:

/image/0Vs5p.png

and this is with the regex expression:

local count, size, modifier = string.match(message, "^!(%d+)[dD](%d+)+?(%d+)$")

As you can see, with the modifier it will work just fine. However, remove the modifier the regex expression still thinks that it is "XdY+Z" and so with "1d20" it think it is "1d2+0". It will think 1d200 is "1d20+0", etc. I've tried moving around the optional character "?" but it just causes the expression to not work at all. If I do !1d2 it doesn't work. It's almost as if the optional character NEEDS to be there?

感谢您提前提供的帮助,我一直在正则表达式方面遇到困难。

最佳答案

local function dice(input)
   local count, size, modifier = input:match"^!(%d+)[dD](%d+)%+?(%d*)$"
   if count then
      return tonumber(count), tonumber(size), tonumber("0"..modifier)
   end
end

for _, input in ipairs{"!1d6", "!1d24", "!1d200", "!1d2+4", "!1d20+24"} do
   print(input, dice(input))
end

输出:

!1d6     1  6    0
!1d24    1  24   0
!1d200   1  200  0
!1d2+4   1  2    4
!1d20+24 1  20   24

关于用于识别 XdY+Z OR XdY 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41092941/

相关文章:

regex - 如何在vim中过滤一些多行语句

lua - 为什么 Lua 算术不等于自身?

java - 正则表达式返回不期望的结果

python - 带有 Action 的基于字典的类开关语句

postgresql - 从 lapis 连接到 postgresql

c - Lua C API - 将属性映射到函数

Luabind - 无法找到 Lua 库

regex - 否定速记字符类的意外工作

regex - 替补中的坏旗

ruby - 如何理解 gsub(/^.*\//, '' ) 或正则表达式