用 Lua 从文本文件中获取文件名

我将文件名保存为一个 Lua 文本文件,并想要在之后的文本文件中搜索文件名。我的问题是,我只会得到搜索到的字符串,而不是整个文件名。

这是我的代码:

local file,err = io.open("C:\\Users\\lamu7789\\Documents\\Lua_Plugins\\test_file_reader   \\channels.txt", 'w')
if file then
  for dir in io.popen([[dir "C:\Users\lamu7789\Documents\Lua_Plugins\test_file_reader\textfiles" /b]]):lines() do
    file:write(dir.."\n")
  end
 file:close()
else
 print("error: ", err)
end

channel = "0x"..string.upper("10")

local file = io.open("C:\\Users\\lamu7789\\Documents\\Lua_Plugins\\test_file_reader\\channels.txt", "rb")
if not file then return nil end
local String = file:read "*a"
local name = String:match(channel)
print(name)
file:close()

在这个例子中,我只得到了"0x10"。 这是路径的样子,以及"print(String)"输出的内容:

enter image description here

我想要得到的是像这样的结果:"0x10_address_second.txt"。在这里出了什么问题? 感谢您的帮助。

原文链接 https://stackoverflow.com/questions/69554661

点赞
stackoverflow用户5189899
stackoverflow用户5189899

你需要像这样匹配完整的名称:

channel = "0x10[_%w]+.txt"
2021-10-13 11:49:02
stackoverflow用户2858170
stackoverflow用户2858170

string.match返回捕获的结果。在你的情况下,这是"0x10"

如果你想捕获整行,你需要修改你的匹配模式。

local s = "0x7E_address_first.txt\n0x10_address_second.txt\n"
print(s:match("0x7E[^\n]*"))
print(s:match("0x10[^\n]*"))

这将捕获你的起始字符后跟任何不是换行符的字符。

请参考https://www.lua.org/manual/5.4/manual.html#pdf-string.match

2021-10-13 11:49:14