Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Lua中反转string.find()或string.gmatch?_Lua - Fatal编程技术网

在Lua中反转string.find()或string.gmatch?

在Lua中反转string.find()或string.gmatch?,lua,Lua,我有一个字符串,其中包含如下内容: ##### abc 'foo' /path/to/filename:1 ##### abc 'bar' /path/to/filename:1 字符串可能非常长(例如,50行),并且不会经常更改 我想获取单引号之间最后出现的文本(bar,在本例中)。这类似于其他人的Python(除了Lua中的答案不适用于我,如下所示) 我可以解析每一行,将结果放入一个数组,然后只取数组的最后一个元素,但这对我来说并不优雅: local text = [[ #####

我有一个字符串,其中包含如下内容:

##### abc 'foo'
/path/to/filename:1
##### abc 'bar'
/path/to/filename:1
字符串可能非常长(例如,50行),并且不会经常更改

我想获取单引号之间最后出现的文本(
bar
,在本例中)。这类似于其他人的Python(除了Lua中的答案不适用于我,如下所示)

我可以解析每一行,将结果放入一个数组,然后只取数组的最后一个元素,但这对我来说并不优雅:

local text = [[ ##### abc 'foo' /path/to/filename:1 ##### abc 'bar' /path/to/filename:1 ]] local arr = {} local pattern = "abc '([^']+)'" for s in text:gmatch(pattern) do table.insert(arr, s) end print('last:', arr[#arr]) 本地文本=[[ #####abc‘foo’ /路径/到/文件名:1 #####abc‘酒吧’ /路径/到/文件名:1 ]] 本地arr={} local pattern=“abc'([^']+)” 对于文本中的s:gmatch(模式)do 表.插入(arr,s) 结束 打印('last:',arr[#arr]) 我对使用Lua字符串模式从末尾搜索字符串感兴趣。我在下面尝试的模式是从头开始,而不是结束:

local text = [[ ##### abc 'foo' /path/to/filename:1 ##### abc 'bar' /path/to/filename:1 ]] -- FIXME: pattern searches from beginning local pattern = "abc '([^']+)'.*$" local s = text:gmatch(pattern)() assert(s == 'bar', 'expected "bar" but saw "'..s..'"') print('last:', s) 本地文本=[[ #####abc‘foo’ /路径/到/文件名:1 #####abc‘酒吧’ /路径/到/文件名:1 ]] --FIXME:从一开始就进行模式搜索 local pattern=“abc'([^']+)'*$” 本地s=文本:gmatch(模式)() 断言(s=='bar','应为“bar”,但看到“…s…”) 打印('last:',s) 这将产生:

input:12: expected "bar" but saw "foo" 输入:12:预期为“bar”,但看到“foo” 什么字符串模式指定了我要查找的“反向搜索”?

您可以使用

local pattern = ".*abc '([^']+)'"
*
是贪婪的,所以它在匹配之前会尽可能多地咀嚼(在这种情况下,它会咀嚼所有先前的匹配,并给出最后一个)

或者,如果你真的想要,你也可以反转你的字符串和(某种程度上)你的模式,但我认为最好依靠贪婪的
*
:p

pattern = "'([^']+)' cba"
print(text:reverse():gmatch(pattern)())           -- rab
print(text:reverse():gmatch(pattern)():reverse()) -- bar