【问题标题】:Look for multiple patterns with string.gsub使用 string.gsub 查找多个模式
【发布时间】:2014-09-21 17:36:12
【问题描述】:

我正在开发一个绘图程序,需要将线条的功能打印到屏幕上。但是,如果数学函数在该行的函数中(例如:)

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

然后我想删除“数学”。部分。我还想删除函数中的任何空格,以及我将来可能想到的其他模式。这是我目前拥有的(当然是简化的)

local func = "math.atan( x )"
print(func:gsub("[math%. ]", "")) --look for math. or a space
--OUTPUT: n(x)

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

【问题讨论】:

  • 您的模式匹配单个字符 math. 和空格,而不是 math.。如果不多次调用gsub,就无法做到这一点

标签: string lua gsub


【解决方案1】:

最简单的方法就是将一堆 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"))

如果您稍后确实添加了模式,请记住转义您的百分号。

【讨论】:

    猜你喜欢
    • 2016-02-15
    • 1970-01-01
    • 2014-10-06
    • 2014-11-15
    • 2023-01-28
    • 2011-05-30
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多