2015-10-15 51 views
1

我试图打开一个文件并搜索特定的字符串,并将我的内容与该特定字符串关联以备将来使用并再次保存该文件。如何在lua中搜索文件的内容

到目前为止,我设法打开一个文件并将内容写入文件。但我正在寻找逻辑来搜索文件的内容并查找特定的字符串并将该数据与该字符串相关联。它更像是查找表以供将来参考。到目前为止我的代码看起来像这样

--write something to a file 
function wrt2file(arg1) 
    file=io.open("/test.txt","a+") 
    file:write(arg1) 
    file:close() 
end 

--to search for a string and associate a new string to it 
function search(arg1,arg2,arg3) 
--i m looking for a function which will search for the string(arg1) in the file(arg2) and stick arg3 that location so that it can be used as a look uptable. 

end 
wrt2file("hello") 
local content="hello" 
search(content,"hi.txt","world") 

如何做到这一点?

+0

你是什么意思与“将我的内容关联到该特定的字符串以供将来使用”?你可以举例说明在调用search()之前和之后的“hi.txt”的内容吗? –

+0

感谢您的回复 我正在寻找一个特定的字符串,并添加一个字符串与它关联 例如 在我现有的文件,说我有字符串称为“水果”。所以我想在这个字符串旁边添加一个名为“apple”的字符串。所以,我搜索“水果”并在它旁边添加一个名为“Apple”的字符串。这样我就可以将字符串“fruit”与苹果关联起来。所以下一次我寻找“水果”我可以访问苹果。 我希望我能够明确我想要达到的目标。谢谢 – codeheadache

回答

1

你应该看看pattern-matching functions in Lua

如果您想要替换文件中的字符串,或者记住文件中字符串的位置,我不清楚。

要更换,你可以使用gsub功能,它的工作原理是这样的:

-- the string you are searching in: 
str = 'an example string with the word hello in it' 

-- search for the word 'hello' and replace it with 'hello world', 
-- and return a new string 
new_str = str:gsub('hello', 'hello world') 

-- new_str is 'an example string with the word hello world in it' 

如果你只是要记住,你可以找到文件中的字符串,你应该使用find,其中工程像这样:

-- the string you are searching in: 
str = 'an example string with the word hello in it' 

-- search for the position of the word 'hello' in str 
offset = str:find('hello') 

-- offset now contains the number 33, which is the position 
-- of the word 'hello' in str 
-- save this position somewhere: 
wrt2file(('world %d'):format(offset)) 
-- your '/test.txt' file now contains 'world 33'