Reverse string.find() or string.gmatch in Lua?
我有一个包含如下内容的字符串:
1 2 3 4 | ##### abc 'foo' /path/to/filename:1 ##### abc 'bar' /path/to/filename:1 |
该字符串可能很长(例如50行),并且不会经常更改。
我想获取单引号(在本示例中为
我可以解析每一行,然后将结果放入数组中,然后只取数组的最后一个元素,但是对我来说,这似乎并不优雅:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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字符串模式从头开始搜索字符串感兴趣。 我在下面尝试的模式从头开始而不是从头开始:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |
这样产生:
1 | input:12: expected"bar" but saw"foo" |
哪种字符串模式指定了我正在寻找的"反向搜索"?
你可以用
1 | local pattern =".*abc '([^']+)'" |
或者,如果您确实想要,也可以反转字符串和(某种)模式,但是我认为最好使用贪婪的
1 2 3 | pattern ="'([^']+)' cba" print(text:reverse():gmatch(pattern)()) -- rab print(text:reverse():gmatch(pattern)():reverse()) -- bar |