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

我正在为一个业余项目短语一个字符串,我是从这个网站上的代码片段自学的,对于这个问题很难解决。我希望你们能帮忙。

我有一个包含许多行并且每一行都有一定格式的大型字符串。

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

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

每一行看起来像这样...

3x Rivendell Minstrel (The Hunt for Gollum)

我想要做一个表,如上面的行所示。

table = {}
  table['The Hunt for Gollum'].card = 'Rivendell Minstrel'
  table['The Hunt for Gollum'].count = 3

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

我尝试了很多东西..像这样...

word=str:match("%((%a+)%)")

但是如果有空格,它会出错...

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

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

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

key = string.gsub(card2Fetch, "%s+", "") -- 删除所有空格
    key=key:match("%((%a+)%)") -- 获取()之间的内容
    print(key) -- 打印 "TheHuntforGollum"

有没有办法从中获取"The Hunt for Gollum"文本,包括空格?

点赞
用户107090
用户107090

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

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

该模式的含义是:在x之前捕获一连串数字,跳过空格,捕获一切直到空格后跟着左括号,最后捕获一切直到右括号。

2018-05-21 10:06:25