【问题标题】:Get numerical values txt file using delimiters使用分隔符获取数值 txt 文件
【发布时间】:2015-04-25 21:06:21
【问题描述】:

我有一个带有以下文本的 txt 文件:

5;2;8;3;

我需要获取数值,使用; 作为分隔符,并将它们放入一个数组中。这是如何实现的?

【问题讨论】:

  • tbl = assert(load('return {'..file_content:gsub(';',',')..'}'))()
  • @EgorSkriptunoff,不需要用逗号替换分号。
  • @lhf - 确实!谢谢。

标签: lua lua-patterns


【解决方案1】:

最简单的方法是使用string.gmatch 来匹配数字:

local example = "5;2;8;3;"
for i in string.gmatch(example, "%d+") do
  print(i)
end

输出:

5                                                                                                                                                                   
2                                                                                                                                                                   
8                                                                                                                                                                   
3 

具有特定Split 功能的“更难”方式:

function split(str, delimiter)
    local result = {}
    local regex = string.format("([^%s]+)%s", delimiter, delimiter)
    for entry in str:gmatch(regex) do
        table.insert(result, entry)
    end
    return result
end

local split_ex = split(example, ";")
print(unpack(split_ex))

输出:

5       2       8       3 

看看sample program here

【讨论】:

  • 非常感谢您的快速回答。
  • 太好了,请考虑接受我的回答,也许,编辑您的问题以包含您尝试过的内容(1 个示例就足够了)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
  • 2016-03-05
相关资源
最近更新 更多