Lua中的字符串算术操作分割

以下是Lua中的字符串算术操作。

local str ='x+abc*def+y^z+10'

这个字符串可不可以被分割,使得个别的变量或数字会出现?例如,如果把字符串str分成表s,那么输出将是

s[1] = x
s[2] = abc
s[3] = def
s[4] = y
s[5] = z
s[6] = 10

分割的操作将使用运算符+,-,*,\,^,%

点赞
用户2858170
用户2858170

你可以使用 string.gmatch 迭代你的字符串。 你可以添加其他操作符到 pattern 中。

参考https://www.lua.org/manual/5.3/manual.html#6.4.1

local str ='x+abc*def+y^z+10'
local s = {}

for operand in str:gmatch('[^%+%*%^]+') do
  table.insert(s, operand)
end
2019-08-13 17:45:47
用户7396148
用户7396148

你可以使用 string.gmatch 来完成你想要的操作。你可以使用模式 %+%-%*%^/

local str ='x+abc*def+y^z+10'
local s = {}
for value in str:gmatch("[%+%-%*%^/]*(%w*)[%+%-%*%^/]*") do
  s[#s + 1] = value
end
print(unpack(s))

同时请注意,如果需要 \ 作为运算符,需要使用额外的 \ 进行转义。

了解更多关于 Lua 模式的知识:understanding_lua_patterns

2019-08-13 17:49:52
用户107090
用户107090

也可以尝试这个更简单的模式:

local str ='x+(abc*def)+y^z+10'
for w in str:gmatch("%w+") do
        print(w)
end
2019-08-14 10:15:35