Lua string.gsub替换模式

时间:2014-09-21 20:31:03

标签: string lua reverse gsub

我正在制作图形计算器程序。我有一个显示'y ='函数的图表。

如果找到诸如'x * 5'之类的模式(其中x乘以某个东西,但首先给出x),我想用5x替换它。这就是我现在所拥有的。

local func = "x * 5"
print(func:gsub("%*", ""):gsub(" ", ""):gsub("x%d+", "%d+x"))

--[[
    get rid of the '*' symbol, get rid of spaces, then 
    replace x(digit) with (digit)x

    EXPECTED OUTPUT: 5x, OUTPUT: d+x
]]

我在想我可能会使用string.reverse函数,但我不知道如何处理它。有人可以帮忙吗?

更新:这就是我现在所拥有的。它正在输出'2x.5'

local func = "x * 5"
print(func:gsub("%*", ""):gsub(" ", ""):gsub("x%d+", function(match) return match:sub(2) .. match:sub(1, 1))

1 个答案:

答案 0 :(得分:0)

我实际上找到了一种简单的方法。我没有解析显示它的功能(基本上从5 * x到5x),而是决定采用完全相反的方式。我做了它,所以你可以在函数中输入3x,然后脚本将它变成3 * x然后使用loadstring执行它。谢谢你的帮助。

相关问题