我有一个包含以下内容的字符串:
##### 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])
我想使用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)
这将产生以下结果:
input:12: expected "bar" but saw "foo"
哪个字符串模式指定了我要查找的“反向搜索”?