【问题标题】:Lua String SplitLua 字符串拆分
【发布时间】:2013-04-14 07:15:06
【问题描述】:

您好,我在 JavaScript 中有这个函数:

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

这样做是需要一个字符串,例如“Hello my name is bob”,然后返回 toBlur = "你好,我的名字是" and lastWord = "bob"

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

【问题讨论】:

    标签: lua coronasdk


    【解决方案1】:

    你可以使用 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 习惯用法,用于将元素附加到数组的末尾。

    【讨论】:

    • 感谢您的回复,使用代码的第一位return string.match(data, "^(.*)[ ][^ ]*$") 我能够返回字符串的第一位,我将如何进行单独的字符串匹配以仅返回最后一个单词?
    • 您实际上可以在一次调用中完成这两项工作:return string.match(data, "^(.*)[ ]([^ ]*)$") 将有两个返回值(每个捕获组一个)。如果您在单独的调用中需要它,只需一次使用一个捕获组。
    • 我正在考虑将两个单独的值返回给两个不同的变量local hiddentxt = string.match(dataTable.lines[i].text, "^(.*)[ ][^ ]*$"),所以在本例中它将返回“Hello my name is”,我想要另一个 local showntxt = ..,它将返回“bob”为我需要稍微不同地对待不同变量中的值
    • 啊,我想我知道你的意思了,像这样local hiddentxt, showntxt = string.match(dataTable.lines[i].text, "^(.*)[ ]([^ ]*)$")返回两个值
    • @Tam2 为了挑剔,我认为这不会首先修剪字符串。要合并它,可能会使用 ^[ ]*(.*)[ ]([^ ]*)[ ]*$ 之类的东西。这应该确保空格与捕获组的outside 匹配,因此它们不会成为结果的一部分。 (不过我可能是错的,因为我还没有真正使用过这么多,上周才开始使用 Lua。)
    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2018-06-01
    • 1970-01-01
    • 2016-08-25
    • 2021-06-10
    • 2015-01-16
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多