使用单个模式捕获 lua 脚本中文件中包含的多个值

Nim*_*iya 1 lua

我有一个文本文件,其中包含格式为“年份”、“城市”、“国家”的数据。数据每行写入一年、城市、国家。例如-:

  • 1896年,希腊雅典
  • 1900年,法国巴黎

以前我使用的是这样硬编码的数据

local data = {} 

data[1] = { year = 1896, city = "Athens", country = "Greece" }
data[2] = { year = 1900, city = "Paris", country = "France" }
data[3] = { year = 1904, city = "St Louis", country = "USA" }
data[4] = { year = 1908, city = "London", country = "UK" }
data[5] = { year = 1912, city = "Stockholm", country = "Sweden" }
data[6] = { year = 1920, city = "Antwerp", country = "Netherlands" }

Run Code Online (Sandbox Code Playgroud)

现在我需要从文件中读取行并将值获取到私有知识库“local data = {}”

无法弄清楚如何使用文件中的数据中的单个模式捕获多个值。

到目前为止我的代码是

local path = system.pathForFile( "olympicData.txt", system.ResourceDirectory )
 
-- Open the file handle
local file, errorString = io.open( path, "r" )
 
if not file then
    -- Error occurred; output the cause
    print( "File error: " .. errorString )
else
    -- Read each line of the file
    for line in file:lines() do
        local i, value = line:match("%d")
        table.insert(data, i)
        
    -- Close the file
    io.close(file)
    
end
 
file = nil
Run Code Online (Sandbox Code Playgroud)

Pig*_*let 5

鉴于您读过这样的行

1896, Athens, Greece
Run Code Online (Sandbox Code Playgroud)

您可以简单地使用捕获来获取所需的值。

https://www.lua.org/manual/5.3/manual.html#6.4.1

捕获:模式可以包含括在括号中的子模式;他们描述了捕获。当匹配成功时,匹配捕获的主题字符串的子字符串将被存储(捕获)以供将来使用。捕获根据其左括号进行编号。例如,在模式“(a*(.)%w(%s*))”中,匹配“a*(.)%w(%s*)”的字符串部分存储为第一个捕获(因此编号为 1);匹配“.”的字符 被捕获的编号为 2,并且匹配“%s*”的部分的编号为 3。

作为一种特殊情况,空的 capture() 捕获当前字符串位置(一个数字)。例如,如果我们对字符串“flaaap”应用模式“()aa()”,则会有两个捕获:3 和 5。

local example = "1896, Athens, Greece"
local year, city, country = example:match("(%d+), (%w+), (%w+)")
print(year, city, country)
Run Code Online (Sandbox Code Playgroud)