读取字符串时如何匹配浮点数

当处理字符串时,如何匹配浮点数例如 1.234 或使用科学记数法 1.23e04

作为示例,假设我希望从以下数据文件中读取数字:

0.0 1.295e-03
0.1 1.276e-03
0.2 1.261e-03
0.3 1.247e-03
0.4 1.232e-03
0.5 1.218e-03

目前,我编写了自己的函数来将每行转换为包含数字的行,但它不是非常优雅,也不可移植:布局不同的数据文件将导致错误。

以下是一个简单的示例,读取已发布的数据文件并将数字打印到屏幕:

function read_line(str)
   local a, b, c, d, e = str:match(
      "^%s*(%d+)%.(%d+)%s+(%d+)%.(%d+)[Ee]%-*(%d+)")
   if str:match("%-") then
      e = -tonumber(e)
   end
   local v1 = a + .1*b
   local v2 = (c + .001*d) * 10^e
   return v1, v2
end

for line in io.lines("data.txt") do
   print(read_line(line))
end

这将得到以下结果:

0   0.001295
0.1 0.001276
0.2 0.001261
0.3 0.001247
0.4 0.001232
0.5 0.001218

这确实是我想要实现的结果,但是有没有更优雅和通用的方法来解决这个问题?

注意: 数据文件可能具有两个以上的数字列,并且可以同时具有浮点表示和“E记数法”。

点赞
用户1009479
用户1009479

假设每行只包含由空格分隔的数字,你可以让 tonumber 来完成匹配数字的繁重工作:

function split_number(str)
    local t = {}
    for n in str:gmatch("%S+") do
        table.insert(t, tonumber(n))
    end
    return table.unpack(t)
end

for line in io.lines("data.txt") do
    print(split_number(line))
end
2015-04-05 17:35:20
用户513355
用户513355

这适用于在 lua REPL 上操作。

a = tonumber('4534.432')
b = tonumber('4534.432')
a==b

因此,答案就是简单地使用 tonumber。

2015-04-05 17:45:38
用户107090
用户107090

Lua可以直接读取数字:

f=assert(io.open("data.txt"))
while true do
    local a,b=f:read("*n","*n")
    if b==nil then break end
    print(a,b)
end
f:close()
2015-04-05 21:46:06