【问题标题】:Split a string by \n or \r using string.gmatch()使用 string.gmatch() 通过 \n 或 \r 拆分字符串
【发布时间】:2015-09-29 14:48:21
【问题描述】:

一个简单的模式应该可以完成这项工作,但我无法想出/找到可行的方法。 我希望有这样的东西:

lines = string.gmatch(string, "^\r\n") 

【问题讨论】:

    标签: string lua lua-patterns


    【解决方案1】:

    要将字符串拆分为表格(数组),您可以使用以下内容:

    str = "qwe\nasd\rzxc"
    lines = {}
    for s in str:gmatch("[^\r\n]+") do
        table.insert(lines, s)
    end
    

    【讨论】:

      【解决方案2】:

      重要的一点 - 使用 gmatch 删除分隔符的解决方案不匹配两个换行符之间的空字符串,所以如果你想像正常的拆分实现一样保留这些(例如,比较两个文档中的行)你最好匹配分隔符,例如在此示例中:

      function string:split(delimiter)
        local result = { }
        local from  = 1
        local delim_from, delim_to = string.find( self, delimiter, from  )
        while delim_from do
          table.insert( result, string.sub( self, from , delim_from-1 ) )
          from  = delim_to + 1
          delim_from, delim_to = string.find( self, delimiter, from  )
        end
        table.insert( result, string.sub( self, from  ) )
        return result
      end
      

      归功于https://gist.github.com/jaredallard/ddb152179831dd23b230。

      【讨论】:

        【解决方案3】:

        我找到了答案:使用 "[^\r\n]+"('+' 用于跳过空行)。

        之前,我故意避免使用括号,因为我认为它表示不支持转义的特殊字符串文字。嗯,那是不正确的。这样做是双括号。
        Lua string.gsub() by '%s' or '\n' pattern

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-11-23
          • 1970-01-01
          • 1970-01-01
          • 2016-04-28
          • 1970-01-01
          • 2020-07-18
          • 1970-01-01
          相关资源
          最近更新 更多