使用string.gsub查找多个模式。

我正在编写一个绘图程序,需要将直线的函数打印到屏幕上。然而,如果线的函数中有数学函数(例如:)

function(x) return math.atan(x) end

那么我想去掉“math。”部分,还想去掉函数中的任何空格,以及我将来可能想到的其他模式。这是我目前的代码(当然是简化过的)

local func = "math.atan( x )"
print(func:gsub("[math%. ]", "")) --查找math。或空格
-- 输出:n(x)

我意识到我不需要括号之间的空格,但这些只是为了测试目的而存在。我希望输出显示为“atan(x)”。

点赞
用户802794
用户802794

最简单的方法就是将多个 gsub 调用链接在一起。在这种情况下,可以使用:

local func = "math.atan( x )"
print(func:gsub("math", ""):gsub("%s", "")) --> atan(x)

甚至可以编写一个简写方法来隐藏 gsub 链接:

local function chainremove(source, ...)
    for index, value in ipairs({...}) do
        source = source:gsub(value, "")
    end

    return source
end

这样就可以将“未来可能想到的其他模式”概念作为表面上的单个方法调用:

local func = "math.atan( x )"
print(chainremove(func, "math", "%s"))

如果以后添加模式,请记住转义百分号。

2014-09-22 00:53:19