String 读取字符串时如何匹配浮点数
在处理字符串时,如何匹配像String 读取字符串时如何匹配浮点数,string,lua,lua-patterns,String,Lua,Lua Patterns,在处理字符串时,如何匹配像1.234这样的浮点数或像1.23e04这样使用“E表示法”的浮点数 例如,假设我想从如下数据文件中读取数字: 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 目前,我编写了自己的函数来转换每一行所包含的数字,但它不是很优雅,也不可移植:具有不同“布局”的数据文件将产生错误 下面是一个简单的示例,它读取已显示的数据文件并打印以筛选数字: functi
1.234
这样的浮点数或像1.23e04
这样使用“E表示法”的浮点数
例如,假设我想从如下数据文件中读取数字:
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表示法”。假设每一行只包含空格分隔的数字,您可以让
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
这适用于lua REPL
a = tonumber('4534.432')
b = tonumber('4534.432')
a==b
因此,您的答案只是使用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()
tonumber解析浮动本身:
对于字符串中的单词。gmatch(“0.0 1.295e-03”,“[^%s]+”)请打印(tonumber(word))结束
谢谢您的回答。然而,数据文件中的第一行通常由描述数字列的单词组成。我是否可以从第二行开始读取,以便仍然从1而不是从2对数组进行索引(因为如果split\u number
读取单词,它将返回nil
)?@PierPaolo似乎没有问题。跳过第一行的方法不止一种,根据您的具体问题选择一种优雅的方法。