从 lua 中的字符串中提取数据 - 子字符串和数字

aJy*_*nks 2 lua

我正在尝试为一个爱好项目编写一个字符串,并且我是通过该网站的代码片段自学的,并且很难解决这个问题。我希望你们能帮忙。

我有一个大字符串,包含很多行,每行都有一定的格式。

我可以使用此代码获取字符串中的每一行...

for line in string.gmatch(deckData,'[^\r\n]+') do
    print(line) end
Run Code Online (Sandbox Code Playgroud)

每行看起来都是这样的......

3x 瑞文戴尔吟游诗人(追捕咕噜)

我想做的是为上面的行制作一个看起来像这样的表格。

table = {}
  table['The Hunt for Gollum'].card = 'Rivendell Minstrel'
  table['The Hunt for Gollum'].count = 3
Run Code Online (Sandbox Code Playgroud)

所以我的想法是提取括号内的所有内容,然后提取数值。然后删除该行中的前 4 个字符,因为它始终是 '1x '、'2x ' 或 '3x '

我尝试了很多事情..像这样......

word=str:match("%((%a+)%)")
Run Code Online (Sandbox Code Playgroud)

但如果有空格就会出错...

我的测试代码现在看起来像这样......

line = '3x  Rivendell Minstrel (The Hunt for Gollum)'
    num = line:gsub('%D+', '')
    print(num) -- Prints "3"

card2Fetch = string.sub(line, 5)
    print(card2Fetch) -- Prints "Rivendell Minstrel (The Hunt for Gollum)"

key = string.gsub(card2Fetch, "%s+", "") -- Remove all Spaces
    key=key:match("%((%a+)%)") -- Fetch between ()s
    print(key) -- Prints "TheHuntforGollum"
Run Code Online (Sandbox Code Playgroud)

有什么想法如何将“寻找咕噜”文本从那里(包括空格)中取出吗?

lhf*_*lhf 5

尝试使用单一模式捕获所有字段:

x,y,z=line:match("(%d+)x%s+(.-)%s+%((.*)%)")
t = {}
t[z] = {}
t[z].card = y
t[z].count = x
Run Code Online (Sandbox Code Playgroud)

该模式如下:捕获 之前的一串数字x,跳过空格,捕获空格之前的所有内容,后跟左括号,最后捕获右括号之前的所有内容。