Lua String Split

时间:2013-04-13 22:31:04

标签: lua corona

您好我在JavaScript中使用此功能:

    function blur(data) {
    var trimdata = trim(data);
    var dataSplit = trimdata.split(" ");
    var lastWord = dataSplit.pop();
    var toBlur = dataSplit.join(" ");
 }

这是一个字符串,如“你好我的名字是鲍勃”,并将返回 toBlur =“Hello my name is”和lastWord =“bob”

有没有办法可以在Lua中重写这个?

1 个答案:

答案 0 :(得分:3)

您可以使用Lua的模式匹配工具:

function blur(data) do
    return string.match(data, "^(.*)[ ][^ ]*$")
end

该模式如何运作?

^      # start matching at the beginning of the string
(      # open a capturing group ... what is matched inside will be returned
  .*   # as many arbitrary characters as possible
)      # end of capturing group
[ ]    # a single literal space (you could omit the square brackets, but I think
       # they increase readability
[^ ]   # match anything BUT literal spaces... as many as possible
$      # marks the end of the input string

所以[ ][^ ]*$必须匹配最后一个单词和前一个空格。因此,(.*)将返回其前面的所有内容。

要更直接地翻译JavaScript,请先注意Lua中没有split函数。但有table.concat,其作用类似于join。由于您必须手动进行拆分,因此您可能会再次使用模式:

function blur(data) do
    local words = {}
    for m in string.gmatch("[^ ]+") do
        words[#words+1] = m
    end
    words[#words] = nil     -- pops the last word
    return table.concat(words, " ")
end

gmatch不会立即为您提供表格,而是对所有匹配项进行迭代。因此,您将它们添加到您自己的临时表中,并在其上调用concatwords[#words+1] = ...是一个将元素附加到数组末尾的Lua习语。